G Suite Business customers can preview App Maker. Ask your domain admin to apply for early access.

App Maker Client API - General

Accessibility

Utilities for any assistive technologies the user may have active.

Methods

Name Return Value Description
announce(
  text:string)
undefined

Announces the given text to the screen reader.

Back to Top

Analytics

Analytics service allows tracking of user actions for statistical purposes. See the Google Analytics Event Tracking documentation for more information.

You can access this object from the global app object.

 var analytics = app.analytics;
 // Records a page view for "NewPage1"
 analytics.page(app.pages.NewPage1.name);
 // Records a custom event
 analytics.event("Videos", "Video Load Time", "Gone With the Wind", 40);

Methods

Name Return Value Description
dimension(
  index:int,
  value:string)
undefined

Sets an analytics custom dimension. You can read more about custom dimensions in the Google Analytics documentation.

event(
  category:string,
  action:string,
  label:string,
  value:int)
undefined

Records a generic event.

page(
  name:string)
undefined

Records a page view.

timing(
  category:string,
  variable:string,
  time:int,
  label:string)
undefined

Constructs and sends the user timing tracking call to the Google Analytics Tracking Code. See User Timings - Web Tracking for more information.

Back to Top

App

Global state of application runtime.

This is used to access all information about your currently running application. It is accessed on from the app object, which is available in any client script.

Example uses:

 // Get the current user of the application
 var user = app.user;
 // Gets the datasource named "awesome".
 var awesomeDatasource = app.datasources.awesome;
 // Sets a new current page
 app.showPage(app.pages.NewPage1);

Properties

Name Type Description
accessibility Accessibility Utilities for any assistive technologies the user may have active.
analytics Analytics Analytics object for the application.
appKey string The Drive file ID of the application. This can be used to differentiate applications and is the same value for all deployments of an application.
currentPage Panel Current page being shown by the application.
datasources PropertyMap All datasources defined in the application.
models PropertyMap All models defined in the application.
pageFragments PropertyMap All page fragments defined in the application.
pages PropertyMap All pages defined in the application.
sanitizer Sanitizer Utilities for HTML and URL sanitization.
user User User object showing the current user of the application.

Methods

Name Return Value Description
closeDialog() undefined

Closes the currently displayed dialog.

Example:

app.closeDialog();

showDialog(
  rootPage:LayoutWidget)
undefined

Shows a centered dialog using rootPage as the content. A root page is either a page or a page fragment. You cannot show a page which is currently being shown.

Example:

   app.showDialog(app.pages.NewPage1);
If showDialog() is called when a dialog is already showing, the new dialog will be shown on top of that dialog.

showPage(
  rootPage:LayoutWidget)
undefined

Shows the given page, unloads the current page. Note that it works for pages only, not for page fragments.

Example:

   app.showPage(app.pages.NewPage1);

Back to Top

AppLoader

This is passed into the onAppStart() script and allows you to cancel and resume the loading of your application. It is useful if you want to delay loading your UI until some data is loaded.

For example, suppose you store a preferred starting page for each user in a user preference record. The following example loads that datasource and displays the appropriate page based on the results.

   var datasource = app.datasources.MyUserDatasource;
   // Stop app from loading until the datasource loads.
   loader.suspendLoad();
   datasource.load(function() {
     app.showPage(datasource.item.StartPage);
     // Continue load now that data is loaded and page is set.
     loader.resumeLoad();
   });

Methods

Name Return Value Description
resumeLoad() undefined

Resumes loading your app after suspendLoad() was called.

suspendLoad() undefined

Temporarily suspends loading your App Maker app. You can resume the load later using resumeLoad().

Back to Top

Callback

Client-side asynchronous callback for client script records. The success([Record]) and failure(String) functions asynchronously return results back to the datasource.

Example using Google APIs (gapi):

  function start() {
    // 2. Initialize the JavaScript client library.
    gapi.client.init({
      'apiKey': 'YOUR_API_KEY',
    }).then(function() {
      // 3. Initialize and make the API request.
      return gapi.client.request({
        'path': 'https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names'
      });
    }).then(function(response) {
      // 4. Map server response to datasource record.
      var record = recordFactory.create();
      record.Result = response.result;
      callback.success([record]);
    }, function(reason) {
      callback.failure('Error: ' + reason.result.error.message);
    });
  }
  // 1. Load the JavaScript client library.
  gapi.load('client', start);

Methods

Name Return Value Description
failure(
  message:string)
undefined

Returns a failure message back to the datasource via callback.

Example:

  gapi.client.request({
    'path': 'https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names'
  }).then(function(response) {
    callback.success([recordFactory.create()]);
  }, function(reason) {
    callback.failure('Error: ' + reason.result.error.message);
  });

success(
  records:Record[])
undefined

Returns an array of this model's records back to the datasource via callback.

Example:

   var record = recordFactory.create();
   record.Name = 'John Doe';
   callback.success([record]);

Back to Top

CreateDataSource

A create datasource is a datasource used to create items in a particular data source. Its item property is always populated by a draft item which can be bound to or set programmatically. This can be useful if you want to create an insert form to allow users to enter values for a new record before it is actually created on the server, or if you want to create a record in a script with some starting values.

A create datasource can be retrieved either from app.datasources.DatasourceName.modes.create or from a widget's widget.datasource.modes.create property.

The following example uses a create datasource to create a new record in its parent datasource, and then retrieves the key of the newly created record in a callback.

 var myCreateDatasource = app.datasources.MyDatasource.modes.create;
 var draft = myCreateDatasource.item;
 draft.Name = "Name";
 draft.Age = 52;

 // Create the new item
 myCreateDatasource.createItem(function(newRecord) {
   // Callback is called after the record is saved, so it now has a key.
   var key = newRecord._key;
   // Do something with the key here.
 }

Properties

Name Type Description
creating boolean Whether an item is currently being created.
deleting boolean Whether an item is currently being deleted.
hasChanges boolean Whether the datasource currently has changes. This will always be true.
item Dynamic Current item in the item set.
itemIndex number Current index in the item set.
items Dynamic[] Loaded item set. Contains one page worth of items, or all of them if not paged.
loaded boolean Whether the items have been loaded.
loading boolean Whether the items are currently loading.
model Model If the items are records, then this is their model.
name string Datasource's name. Can be used to access datasources in relations.

Methods

Name Return Value Description
clearChanges() undefined

Clears the changes to the Create datasource's record.

createItem(
  callback:function(record:Record))
undefined

Creates a new item on its parent datasource. Executes an optional callback function when finished.

Example:

   datasource.modes.create.createItem(function(record) {
     alert("Created new record. Name was: " + record.name);
   });
 

saveChanges(
  callback:function())
undefined

Saves a new record on its parent datasource. Executes an optional callback function when finished.

This will throw an exception if the parent datasource is in manual save mode and has pending changes.

Example:

   datasource.saveChanges(function() {
     alert("Saved new item.");
   });
 

Back to Top

DataSource

Provides access to a set of items which could be records or any other value. Allows paging, creating new items, iterating over items while keeping track of current item, etc.

A datasource can be retrieved either from app.datasources or from a widget's datasource property.

The following example uses a model datasource to create a new record, and then retrieves the key of the newly created record in a callback.

 var myDatasource = app.datasources.MyDatasource;
 var myCreateDatasource = myDatasource.modes.create;
 var draft = myDatasource.modes.create.item;
 draft.Name = "Name";
 draft.Age = 52;
   // Create the new item
 myCreateDatasource.createItem(function(newRecord) {
   // Callback is called after the record is saved, so it now has a key.
   var key = newRecord._key;
   // Do something with the key here.
 }

Properties

Name Type Description
creating boolean Whether an item is currently being created.
deleting boolean Whether an item is currently being deleted.
draft Dynamic Prototype that will be used to create record using createItem(). This prototype record is reset to default state after each call to createItem(). Deprecated: Use the Create Datasource insteadopen_in_new.
firstPage boolean Whether the datasource in on the first page.
hasChanges boolean Whether the datasource currently has changes. This is only applicable if the datasource is in manual save mode.
item Dynamic Current item in the item set.
itemIndex number Current index in the item set.
items Dynamic[] Loaded item set. Contains one page worth of items, or all of them if not paged.
lastPage boolean Whether there are more query results beyond this page.
loaded boolean Whether the items have been loaded.
loading boolean Whether the items are currently loading.
model Model If the items are records, then this is their model.
name string Datasource's name. Can be used to access datasources in relations.
properties PropertyMap User-defined custom properties.
query Query Query used to populate the datasource.
relations PropertyMap Datasources representing relations to and from the current item of this datasource.

Methods

Name Return Value Description
clearChanges() undefined

For a datasource in manual save mode, discards pending changes to the items.

clearDraft() undefined

Clears the draft. This function is called after creating a new record with createItem().
Deprecated: Use clearChanges instead. See the create mode datasource documentation.

createItem(
  callback:function(record:Record))
undefined

Creates a new item, and changes the current item to the newly created item. This is only supported by datasources which can create items, namely query or relation datasources. Executes an optional callback function when finished.

Example:

   datasource.createItem(function(record) {
     alert("Created new record. Name was: " + record.name);
   });
 

deleteItem(
  callback:function())
undefined

Deletes the current record. This is only supported by datasources which can delete records, namely query or relation datasources. The record is immediately removed from the data source and marked as deleted on the client. Executes an optional callback function when finished on the server.

Example:

   datasource.deleteItem(function() {
     alert("Deleted current datasource record.");
   });
 

load(
  callback:function())
undefined

Tells the datasource to fetch data using any query parameters that are currently set. If the datasource is already loaded, reloads the datasource. Executes an optional callback function when finished.

Example:

   datasource.load(function() {
     alert("Loaded datasource.");
   });
 

loadPage(
  page:int,
  callback:function())
undefined

Loads the specified page. This is only supported by query and SQL datasources. If this method, is called again before the results of a previous call have been received from the server, then the previous call results will not change the items in the datasource. However, the callback for the previous call will still be invoked.

nextItem(
  callback:function())
undefined

Selects the next item.

For Query Datasources, if the current item is the last item on the page, then this loads the next page and selects the first item on the newly loaded page.

nextPage(
  callback:function())
undefined

Loads the next page. This is only supported by query and SQL datasources.

prevItem(
  callback:function())
undefined

Selects the previous item.

For Query Datasources, if the current item is the first item on the page, then this loads the previous page and selects the last item on the newly loaded page.

prevPage(
  callback:function())
undefined

Loads the previous page. This is only supported by query and SQL datasources.

saveChanges(
  callback:function())
undefined

For a datasource in manual save mode, saves pending changes to the items. Executes an optional callback function when finished.

Example:

   datasource.saveChanges(function() {
     alert("Saved pending changes.");
   });
 

selectIndex(
  index:int)
undefined

Sets the current item of this datasource to the item at index.

selectKey(
  key:string)
undefined

Sets the item property of this datasource to the record with the specified key. If a record with the key is not loaded in the items of this datasource, the current item is not changed.

Note: Only model datasources support this method.

unload() undefined

Unloads all loaded items so that the item set becomes empty.

Events

Name Description
onItemChange() Called whenever the current item of the datasource changes. This includes once when the datasource loads and sets its initial item, and when a new item is created and selected as the current item.

Note: Many uses of this callback can be achieved more directly using a binding to @datasource.item.

onLoad() Called when the datasource finished loading data. This includes when a new page is loaded.

Note: Many uses of this callback can be achieved more directly using a binding to @datasource.items or @datasource.loaded. For example, if you don''t want to show a widget until data is loaded, you could just associate it to this datasource, and then bind its visible property to @datasource.loaded.

Back to Top

Model

A model object representing the models created or imported in the Model Editor. This is used to access information about the model or it's fields, for example you could access the possible values for a field using app.models.ModelName.fields.FieldName.possibleValues. To access the records of a model, you should use its datasources, either through the datasources property of model, or app.datasources which displays all model datasources.

Properties

Name Type Description
datasources PropertyMap The datasources for this model.
description string Model's description, as specified in the Model Editor.
fields PropertyMap Fields of this model.
name string Model's name, as specified in the Model Editor.
relations PropertyMap Relations from this model.

Back to Top

PropertyMap

Collection of named values where each value is directly accessible as a field. For example, it can be a set of all fields in a model, or a set of all models in an application. Note that adding or removing fields from this object has no effect on the object it represents. So, for example, adding a property to the "fields" property map won't add a field to a model.

This example shows using the _values property on this pages property map to alert() all the page names in the application.

 var allPages = app.pages._values;
 for (var i = 0; i < allPages.length; i++) {
   alert(allPages[i]);
 }

Properties

Name Type Description
<field> Dynamic There is a field for each named value of underlying object.
_values Dynamic[] Alternative way to access the same values, as iterable array.

Back to Top

Query

The query object controls which records are loaded into a datasource and how they are sorted. You can get a Query object by accessing the "query" property of a datasource.

Setting filters

The main function of a query is setting filters. These filters affect what records are returned when load() is called on a datasource. You can set filters on most fields of a model (depending on the type of backing model).

The following example will load the datasource with all the records in NewModel with a name field that starts with "John" and whose age field is greater than 20.

 var datasource = app.datasources.NewModel;
 datasource.query.filters.Name._startsWith = 'John';
 datasource.query.filters.Age._greaterThan = 20;
 datasource.load();

Properties

Name Type Description
filters object Adds filters to the query. Supported filters: equals, notEquals, lessThan, greaterThan, lessThanOrEquals, greaterThanOrEquals, in, notIn, startsWith, notStartsWith, contains, notContains.
var datasource = app.datasources.NewModel;
datasource.query.filters.Name._startsWith = 'John';
datasource.query.filters.Age._greaterThan = 20;
datasource.load();

Filters in and notIn check that the field equals (not equals) any value in a given array.

Filters startsWith, notStartsWith, contains, notContains are only supported for strings.

Filters lessThan, greaterThan, lessThanOrEquals, greaterThanOrEquals are supported for numbers, dates and strings.

keywords string Keywords for full-text search. Search every field (depending on the data backend) for the specified keywords.
pageIndex number Page index to load in this query. Note that page index starts at 1.
pageSize number Number of items to display in a single page.
parameters object The parameters of the query.
sorting object Adds sorting criteria to the query. Note that the order in which criteria are added matters. Supported sorting criteria: ascending, descending.
var datasource = app.datasources.NewModel;
datasource.query.clearSorting()
datasource.query.sorting.Name._ascending();
datasource.query.sorting.Age._descending();
datasource.load();

Methods

Name Return Value Description
clearFilters() undefined

Clears any field filters set on the query of the form fieldName.operator and any relation filters of the form relationEndName. Does not re-execute the query, to do so, call the load method after clearing the filters.

clearSorting() undefined

Remove any added sorting criteria.

Back to Top

Record

Data record. The structure of each data record is defined by a certain model.

Note that in client scripts, unlike server scripts, any changes made to record fields are automatically saved. This is true unless the datasource is in manual save mode.

  • If the model that defines this record has field named FieldName, then the record's data for this field can be read or set using record.FieldName syntax.
  • If the model participates in a relation, then the respective association of this record can be accessed using record.RelationName syntax, which will return either one record or an array of multiple records depending on arity of this relation. NOTE: Use caution when accessing associations like this, because it only works if the association has already been loaded, such as through a binding syntax, or by using record._load(), or from a relation datasource's onLoad() event handler, or by specifying it as a pre-fetched relation on the record's model object.

The following is an example of accessing and modifying a record:

   // Get the record from a datasource.
   var record = app.datasources.MyDatasource.item;
   // Change the record's Age field.
   record.Age = 35;
   // Edit the field Salary in the record's Manager relation.
   record.Manager.Salary += 10000;

The following is an example of repeated fields:

   var record = app.datasources.MyDatasource.item;
   // Get the current searches as a JavaScript array.
   var recentSearches = record.RecentSearches;
   // Add an item to that array.
   recentSearches.push("New Search Term");

The following is an example of one-to-one related fields:

   var employee = app.datasources.Employee.item;
   if (employee.Address == null) {
     // This creates a new related Address record.
     app.datasources.Address.createItem(function(address) {
       employee.Address = address;
       address.ZipCode = 94041;
       address.City = "Mountain View";
     });
   } else {
     // This edits existing related Address record.
     var address = employee.Address;
     address.ZipCode = 94041;
     address.City = "Mountain View";
   }

The following is an example of one-to-many related fields:

   var employee = app.datasources.Employee.item;
   // This creates a new empty array if needed.
   if (employee.PreviousEmployment == null) {
     employee.PreviousEmployment = [];
   }
   // This adds a new related employment record.
   app.datasources.Address.createItem(function(employment) {
     employee.PreviousEmployment.push(employment);
     employment.Title = "Software Engineer";
     employment.StartYear = 1988;
     employment.EndYear = 1995;
   });

Properties

Name Type Description
<field> Dynamic There is a field for each record field or relation.
_key string Identifies a record within a model. This is useful if you want to pass a record to a remote server script. The key for records created in create mode or manual save mode is a temporary key used by the App Maker client and does not represent the actual key that the record will have once it is saved.

Methods

Name Return Value Description
_delete(
  callback:function())
undefined

Deletes this record. Executes an optional callback function when finished.

Example:

   record._delete(function() {
     alert("Record was deleted!");
   });
 

_load<Field>(
  callback:Function)
undefined

There is a load function for each relation field that loads or reloads all associated records for that field.

_reload(
  callback:function())
undefined

Reloads the record from the server. Executes an optional callback function when finished.

This function should be used if the server might have changed this record, and you want the changes to be reflected on the client. This also reloads any currently loaded associations (associations are loaded either through pre-fetching, or the _load relation methods.)

Note that this method should not be called for records that have not been saved or records in manual save mode datasources which have changes.

Example:

   record._reload(function() {
     alert("Reloaded record.");
   });
 

Back to Top

RecordFactory

RecordFactory is used to create a new client-side record on the datasource using its create() function. This object can only be referenced by a client script.

Example:

   var record = recordFactory.create();
   record.Name = 'John Doe';
   return [record];

Methods

Name Return Value Description
create() Record

Creates a new record.

Example:

   var record = recordFactory.create();
   record.Name = 'John Doe';
   return [record];

Back to Top

Sanitizer

Utility to sanitize HTML content and URLs.

HTML sanitization means stripping HTML from a potentially dangerous markup like scripts, applets, frames, etc. URL sanitization means replacing the URL with # if it's not safe (e.g. starts with javascript:).

Methods

Name Return Value Description
sanitizeHtml(
  html:string)
string

Returns a sanitized HTML. This includes stripping unsafe URLs and removing potentially dangerous HTML markup like scripts, applets, frames, etc.

Note: HTML sanitization is a necessary part of any application which operates with the user-supplied HTML, becasue it helps to prevent the application from cross-site scripting (XSS) attacks, script injections, DOM clobbering or any other HTML structural damage.

For example the following HTML:

 <a href="javascript:alert('Dangerous script!');">Unsafe link</a>
 <a href="https://www.google.com">Safe link</a>
 <iframe src="http://www.unsafeurl.com"></iframe>
will be sanitized to:
 <a>Unsafe link</a>
 <a href="https://www.google.com">Safe link</a>

sanitizeUrl(
  url:string)
string

Returns a sanitized URL or # if the URL is not safe. Safe URLs start with http, https, ftp or mailto.

Back to Top

SqlDataSource

Provides access to a set records through a SQL query. Allows paging and iterating over items while keeping track of current item. A SQL datasource must have a SQL query defined, and optionally, a set of named parameters.
For each named parameter, a custom parameter with the same name must be defined. The select clause of the query must define a column for each model field. The SQL query must not include OFFSET and LIMIT clauses. They are handled by App Maker for you through @datasource.query.pageSize and @datasource.query.pageIndex properties.

For example, a query for a calculated model with a single numeric field 'totalEmployees' that counts all employees filtering by status would look like:

 SELECT COUNT(*) as TotalEmployees FROM Employee WHERE Status = :Status
A custom parameter must be defined on this datasource with name 'status'. You can bind to custom parameters using @datasource.parameter path.

SQL datasources are only available for calculated models.

Properties

Name Type Description
creating boolean Whether an item is currently being created.
deleting boolean Whether an item is currently being deleted.
item Dynamic Current item in the item set.
itemIndex number Current index in the item set.
items Dynamic[] Loaded item set. Contains one page worth of items, or all of them if not paged.
lastPage boolean Whether there are more query results beyond this page.
loaded boolean Whether the items have been loaded.
loading boolean Whether the items are currently loading.
model Model If the items are records, then this is their model.
name string Datasource's name. Can be used to access datasources in relations.
properties PropertyMap User-defined custom properties.
query SqlQuery Query parameters to populate the SQL datasource such as page size and page number.

Methods

Name Return Value Description
load(
  callback:function())
undefined

Tells the datasource to fetch data using any query parameters that are currently set. If the datasource is already loaded, reloads the datasource. Executes an optional callback function when finished.

Example:

   datasource.load(function() {
     alert("Loaded datasource.");
   });
 

loadPage(
  page:int,
  callback:function())
undefined

Loads the specified page. This is only supported by query and SQL datasources. If this method, is called again before the results of a previous call have been received from the server, then the previous call results will not change the items in the datasource. However, the callback for the previous call will still be invoked.

nextItem(
  callback:function())
undefined

Selects the next item.

For Query Datasources, if the current item is the last item on the page, then this loads the next page and selects the first item on the newly loaded page.

nextPage(
  callback:function())
undefined

Loads the next page. This is only supported by query and SQL datasources.

prevItem(
  callback:function())
undefined

Selects the previous item.

For Query Datasources, if the current item is the first item on the page, then this loads the previous page and selects the last item on the newly loaded page.

prevPage(
  callback:function())
undefined

Loads the previous page. This is only supported by query and SQL datasources.

selectIndex(
  index:int)
undefined

Sets the current item of this datasource to the item at index.

unload() undefined

Unloads all loaded items so that the item set becomes empty.

Events

Name Description
onItemChange() Called whenever the current item of the datasource changes. This includes once when the datasource loads and sets its initial item, and when a new item is created and selected as the current item.

Note: Many uses of this callback can be achieved more directly using a binding to @datasource.item.

onLoad() Called when the datasource finished loading data. This includes when a new page is loaded.

Note: Many uses of this callback can be achieved more directly using a binding to @datasource.items or @datasource.loaded. For example, if you don''t want to show a widget until data is loaded, you could just associate it to this datasource, and then bind its visible property to @datasource.loaded.

Back to Top

SqlQuery

Controls data binding for SQL datasource queries.

Properties

Name Type Description
pageIndex number Page index to load in this query. Note that page index starts at 1.
pageSize number Number of items to display in a single page.
parameters PropertyMap The parameters of the SQL query.

Back to Top

User

Identifies user currently using the application.

This is stored in the app object. The following example shows a different page if the user is "gus@webscoe.com".

 var user = app.user;
 if (user.email === "gus@webscoe.com") {
   app.showPage(app.pages.SpecialPage);
 }

Properties

Name Type Description
email string User's full email address. For example, "user@example.com".
role PropertyMap Boolean values representing whether the current user has a specific role.
roles string[] Array of role names that the user has.
username string User's login name. For example, "user".

Back to Top