Newer Version Available

This content describes an older version of this product. View Latest

Add an Apex Trigger

The quick start adds a simple change event trigger that shows how to access header and record fields in a change event message.
Before you add and test the trigger, set up debug logging for the Automated Process entity and enable Account for Change Data Capture. See Prerequisites.
  1. In the Developer Console, select File | New | Apex Trigger.
  2. In the Name field, enter a name for the trigger: MyAccountChangeTrigger.
  3. From the dropdown, select the change event object for Account: AccountChangeEvent.
    The trigger is created with the after insert keyword.
  4. Replace the default content of the trigger with the following code.
    This simple trigger writes header and field values to the debug log for each received change event message. The trigger uses the changedFields header field to determine which fields changed in an update operation. The trigger also creates a follow-up task for new accounts.

    The changedFields property is available in Apex saved using API version 47.0 or later.

    Note

  5. To test the trigger, create an account with a name and phone.
  6. Edit the account, change the name, delete the phone value, and save the record.
  7. In Setup, enter Debug Logs in the Quick Find box, then select Debug Logs.
  8. To view the debug logs corresponding to the record creation, click 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.
  9. To view the debug logs corresponding to the record update, click the first log in the list. The output of the System.debug statements looks similar to the following. The account name’s new value is listed. The phone field’s value was deleted, and its value was set to null. Also, because the system updates the LastModifiedDate field when the record is updated, this field is listed in the changedFields field and is part of the debug output.