Callback Methods
Callback methods on Custom Types
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.
In the callback methods on custom types, the current object can be accessed via the this keyword. (see onDelete
for an exception to this rule)
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
)
)
JavaScript equivalent:
{
var self = Structr.get('this');
if (Structr.empty(self.name)) {
Structr.error('User', 'name', 'must_not_be_empty');
}
}
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. The actual changes made to a node can be accessed via the modifications collection in an onSave
method.
onDelete
Called when an instance of this Custom Type is deleted. The error()
function can be used on onDelete
as well.
Note: In the onDelete callback, using the this
keyword will produce an error as the object has already been deleted.
Note: Raising an error()
will trigger a rollback of the transaction.
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.
Global callback methods
Currently there are two predefined global callback methods onStructrLogin
and onStructrLogout
. They are called when a user logs in and out respectively and are executed in a superuser context.
For these two methods Structr will provide the current user in a variable called user
.
Any global schema method called via call()
will stay in the user context of the current user. Methods called via call_privileged()
will run in a superuser context.