Defining a Source Record
The following example shows how to write code for a Source record to implement logic for a CUD Event Handler, which has a CUD Template Operation as its originator. The classes you use to implement event handlers must inherit from the Groovy class with helper functionality that is provided for this purpose.
To define a Source record:
1. In the Source code field, add the following Groovy code:
package com.servicemax.myapp.event_handler

import com.servicemax.core.event_handler.TemplateOperationEventHandler

class EventHandlerSubclass extends TemplateOperationEventHandler {

public Object realExecute(Map<String,Object>params) {

}

}
2. In the originating Operation record for an event handler, the Method field must be set to execute, which is defined in TemplateOperationEventHandler. The method performs preparatory tasks and then calls realExecute, which is a user-provided method that implements the logic for the template. For instance, to change the io_name field in created, updated, or deleted objects:
package com.servicemax.myapp.event_handler

import com.servicemax.core.event_handler.TemplateOperationEventHandler
import com.servicemax.core.Database

class EventHandlerSubclass extends TemplateOperationEventHandler {
static def eventHandlerData = [];

public static void reset() {
eventHandlerData = [];
}

public Object realExecute(Map<String,Object>params) {
affectedMaxObject.io_name = "a new name"
Database.upsert(affectedMaxObject)
logger.info("name changed by event handler")
}
}
* 
The affectedMaxObject variable specifies the record affected by a Template Operation, for example, the deleted record in a Delete operation. The logger variable grants access to a logger.
Event Handler Types
Event Handler records with the Trigger field set to Before are executed before transactions in which related events occur are committed, and both run within the same transaction.
When the Trigger field is set to After, event handlers execute after the transaction in which the event occurs is committed. By default, these event handlers are not running within a transaction, so they start their own transactions, for example, with Max.executeInTransaction. In this case, the transaction associated with affectedMaxObject is already committed, so to use it for actions that require a transaction, query it again:
Max.executeInTransaction {
def recordId = affectedMaxObject.io_uuid
def record = Database.querySingleResult("select * from <object's full identifier> where io_uuid = :id", [id : recordId])
...
}
* 
Before event handlers are preferable, because they run during the same transaction in which the associated event occurs, so all changes are executed automatically. Otherwise, data inconsistencies can be introduced in cases where errors are present in the event handler. After event handlers should be used only in special cases that require the use of a different transaction.
For more information:
Was this helpful?