Asynchronous Apex Triggers for Change Events
You can subscribe to change events on the Lightning Platform using Apex triggers. The change event trigger fires when one or a batch of change events is received. Unlike object triggers, change event triggers run asynchronously after the database transaction is completed. The asynchronous execution makes change event triggers ideal for processing resource-intensive business logic while keeping transaction-based logic in the object trigger. By decoupling the processing of changes, change event triggers can help reduce transaction processing time.
Define a change event trigger with the
after insert
keyword on the change event using this format.
ChangeEventName is the name of the change event, such as AccountChangeEvent, or for the employee custom object, Employee__ChangeEvent.
Change event triggers share these characteristics with platform event triggers.
- They run under the Automated Process entity. As such, debug logs for the trigger are created by the Automated Process entity, and system fields, such as CreatedById and OwnerId, reference Automated Process.
- They are subject to Apex synchronous governor limits.
- They have a maximum batch size of 2,000 event messages (the number of items in
Trigger.New
).
Because fields in a change event message are statically defined, just like in any other Apex type, all record fields are present. Unlike change events received in external CometD apps, Apex change event messages can contain empty (null) fields. Unchanged fields are null, and so are fields that are explicitly set to null in an update.
To figure out which fields were modified, use the
changedFields
header field. It contains a list of record fields that were changed in an update operation.
Adding a change event trigger is as straightforward as adding a trigger for a Salesforce object. You create a trigger on the change event associated with the Employee custom object that you created previously using the Developer Console. The system creates the change event object, Employee__ChangeEvent, when you create a custom object.
- To open the Developer Console:
- Click the quick access menu ( ).
- Click Developer Console.
- In the Developer Console, select File | New | Apex Trigger.
- In the Name field, enter a name for the trigger:
EmployeeChangeTrigger
. - From the dropdown, select the change event object for the Employee custom object: Employee__ChangeEvent. The trigger is created with the
after insert
keyword. - Replace the default content with the following code.
This change event trigger iterates through each received change event message in
Trigger.New
. For each event, the trigger gets a few header fields. If the operation is an update, the trigger also gets the list of fields that were changed by accessing the changedFields
header value. Next, the trigger displays record field values if not null. Finally, it creates a follow-up task for new Employee records.
Now let’s verify manually that the trigger is working. To receive event messages in the trigger, enable the object first on the Change Data Capture page in Setup. In a previous step, you already enabled notifications for Employee, so you can skip that step here. Because debug logs are created under the Automated Process entity, enable debug logs in Setup for this entity for logs to be collected.
- To open Setup in a new tab, click the quick access menu ( ), then click Setup.
- From Setup, enter
Debug Logs
in the Quick Find box, then select Debug Logs. - Click New.
- For Traced Entity Type, select Automated Process.
- Select the time period to collect logs for and the debug level.
- Click Save.
Leave the Debug Logs Setup page open, since you’ll come back to it in a minute. Next, make some changes in Salesforce to fire the change event trigger. Create an Employee record and then update it.
- In a new tab, click the App Launcher ( ), then click Employees.
- Click New.
- Populate the following fields.
- Employee Name:
e-200
- Last Name:
Smith
- First Name:
Joseph
- Tenure:
1
- Employee Name:
- Click Save.
- In the employee record detail page, click Edit.
- Change the First Name field to
Joe
. - Delete the value for Tenure.
- Click Save.
- Switch to the Debug Logs tab and refresh the browser.
- To view the debug logs corresponding to the record creation, click View next to the second log in the list (logs are ordered by most recent first). The output of the
System.debug
statements looks similar to the following.
- To view the debug logs corresponding to the record update, click View next to the first log in the list. The output of the
System.debug
statements looks similar to the following. Because the system updates the LastModifiedDate field when the record is updated, this field is listed as part of the changed fields.
Before you can package or deploy Apex change event triggers to production, you must provide Apex tests and sufficient code coverage.
To ensure that Salesforce record changes in a test method fire change event triggers, enable all entities for Change Data Capture by calling
Test.enableChangeDataCapture()
at the beginning of the test. This method enables all entities only for the test and doesn't affect the Change Data Capture entity selections for the org.
After enabling Change Data Capture, perform some DML operations and then call the
Test.getEventBus().deliver()
method. The method delivers the event messages from the test event bus to the corresponding change event trigger and causes the trigger to fire.
The test method in the class creates an Employee test record and updates the record. Each of these operations fires the trigger on the Employee change event. The test ensures the trigger execution by querying the task created and verifying the count of tasks.
When running the test class in the Developer Console, the debug logs are available in the Logs tab. For Apex tests, there is no need to set up debug logs in Setup for the Automated Process entity.
To create the test class:
- In the Developer Console, select File | New | Apex Class.
- In the Name field, enter a name for the trigger:
TestEmployeeChangeTrigger
. - Replace the default content with the following code.
- Click Run Test. After the test finishes execution, the Tests tab shows the status of the test run.
- Click the Tests tab and expand the Overall Code Coverage pane. The code coverage for EmployeeChangeTrigger is at 100%, which is the result of running this test.
No comments:
Post a Comment