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

Events

An event occurs on the server whenever your app's UI or client-side scripts access or modify data. Server-side scripts don't trigger events, even when loading or saving records. These are data events, not widget events.

Events trigger permissions checks and can execute server-side scripts.

Requests or modifications to multiple records trigger one event for each record affected. For example, the onLoad event triggers for each record returned to the client.

Event types

NameDescription
onLoadAn event that occurs before the server returns a record.
onSaveAn event that occurs after the client applies changes to a record, but before it's saved to the database.
onCreateAn event that occurs after the client creates a record, but before it's saved to the database.
onDeleteAn event that occurs after the client requests deletion of a record, but before it's deleted from the database.

Events and exceptions

When an event occurs, App Maker checks relevant model and relation permissions and executes the event's script, if you've written one. If the permission check fails or the script throws an exception, App Maker cancels the event and returns an error to the client. Canceling an onLoad event prevents the server from returning a record. Cancelling the other events prevents modifications to the database.

Event Scripts

Add event scripts to the Events tab of the model editor. Event scripts have access to a record variable, which represents the record that triggered the event.

Take care when invoking expensive operations in event scripts, such as executing queries or saving records. Many client actions operate on multiple records at once, so your script is likely to run more than once. Try caching to improve your code's performance.

Here are some examples of how to use event scripts for different event types:

onLoad example

You can use onLoad events to track who accesses a record. This example tracks the last person who viewed a record:

var userEmail = Session.getActiveUser().getEmail();
record.LastVisitor = userEmail;
app.saveRecords([record]);

onSave example

You can use onSave events to validate state in your record or to track when it was last modified. This example throws an exception if two record field values are equal:

if (record.ValueOne === record.ValueTwo) {
  throw new Error("valueOne and valueTwo can't be equal");
}

onCreate example

You can use onCreate events to initialize records with values computed on the server. This example initializes a new record with its creation date:

 record.TimeCreated = new Date();

onDelete example

You can use onDelete events to store a backup of the record in another record of a different model:

var backupRecord = app.models.BackupRecords.newRecord();
backupRecord.Name = record.Name;
app.saveRecords([backupRecord]);