Callback Methods

Search
Feedback

Custom Types can implement four pre-defined Callback Methods that are executed when an object of that type is subject to external changes.

A callback method can be implemented in StructrScript or, for more complex implementations, in ServerSide JavaScript. To implement a pre-defined callback method, the name of the method must match the name of the event below. Callback methods can prevent the modification of an object by calling the error() method, which will fail the transaction and cause a 422 Unprocessable Entity error to be sent to the user.

onCreate

Called when a new instance of this Custom Type is created in the database.

Example

The following onCreate script sets the timestamp property of a newly created entity to the current time and date and triggers Geocoding. This example illustrates the syntax of the template expression used in callbacks.

(
    set(this, 'timestamp', now),
    set(this, geocode(this.street, this.city, this.country))
)

The next example illustrates the use of the error() method to prevent the creation of invalid entities in the database.

(
    if(empty(this.name),
        error('User', 'name', 'must_not_be_empty'),
        null,
    )
)

onSave

Called when an instance of this Custom Type is modified (this does not include creation). Just like onCreate above, onSave can prevent the modification of an object with the error() method.

onDelete

Called when an instance of this Custom Type is deleted. The error() function can be used on onDelete as well.

onDownload

Called when a File is downloaded.

Note

You can of course declare more than one method of each type, suffixing the individual methods with a number (e.g. onCreate01, onCreate02, …). This allows you to specify a series of functions that will be executed when a new entity is created.

Graph-Browser

About this article
Last change 2017-02-24
Topics Structr 2.0