Sub topic 7
Reacting to changes with Apex triggers
An Apex trigger on a change event lets you run server-side logic whenever a selected record changes. This chapter assumes you know basic Apex triggers and DML. It also assumes you have enabled CDC for Account (see the enabling chapter) and know the anatomy of a change event.
How change event triggers differ
A change event trigger looks like a normal trigger, but it runs against the event, not the record. Four differences matter:
- The sObject type is the change event type, such as
AccountChangeEvent. For a custom objectInvoice__c, it isInvoice__ChangeEvent. - Only
after insertis supported. Events are immutable, so there is nobefore,update, ordelete. - The trigger runs asynchronously, in its own transaction, as the Automated Process user. It does not run in the transaction that changed the record.
- One trigger invocation can receive a batch of events from many different transactions.
Reading the header in a trigger
Each event exposes ChangeEventHeader as an EventBus.ChangeEventHeader object. The fields you use most are changeType, changedFields, and recordIds. A single event can cover several records when they changed in the same way, so always loop over recordIds.
The trigger below creates a follow-up Task whenever a phone number is updated.
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
List<Task> followUps = new List<Task>();
for (AccountChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
if (header.changeType == 'UPDATE' && header.changedFields.contains('Phone')) {
for (String recordId : header.recordIds) {
followUps.add(new Task(
Subject = 'Verify updated phone number',
WhatId = recordId
));
}
}
}
if (!followUps.isEmpty()) {
insert followUps;
}
}The trigger collects all Tasks in a list and inserts them once, after the loops. This keeps it within DML limits when a bulk load produces many events.
Common errors
- Reading unchanged fields. An update event carries only the changed fields plus the header. Fields you did not change are
nullon the event. This does not mean the value was cleared. To get the full record, query it using the IDs inrecordIds, and bulkify the query. - Checking the wrong thing for updates. Test
changeTypefirst, then usechangedFields. Compare against the field API name, such asPhoneorRegion__c. - Assuming one record per event.
recordIdsis a list. Ignoring all but the first ID silently drops work. - Expecting the same transaction. Delivery is asynchronous. You cannot roll back the original save from this trigger, and the record may have changed again by the time you query it.
- Causing loops. If your trigger updates Account, that update produces another change event. Guard with a check on
changeOriginor on which fields changed, so your own writes do not retrigger the logic.
Failures and retries
If the trigger throws an uncaught exception, the platform can retry the batch. Throwing EventBus.RetryableException asks for a retry explicitly, and it is suited to temporary problems such as a record lock. Retries are limited, so do not use them for permanent errors. Make the trigger idempotent, because the same events may be processed more than once.
Exercise
A change event for an Account update arrives with changedFields containing only Website. In your trigger, event.Phone is null. Does that mean the phone number was removed? How do you check the current value?
Show answer
No. Update events include only the changed fields, so unchanged fields read as null on the event. The phone number was not removed. To see the current value, query the Account by the IDs in header.recordIds, in one bulkified query.
Exercise
Why does the example trigger collect Tasks in a list and insert them after the loops, instead of inserting inside the inner loop?
Show answer
One trigger run can receive many events and many record IDs. Inserting inside the loop would run one DML statement per record and could exceed the DML statement limit. A single insert after the loops uses one statement.