Newer Version Available

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

Trigger Syntax

To define a trigger, use the following syntax:
1trigger TriggerName on ObjectName (trigger_events) {
2                     code_block
3                     }
where trigger_events can be a comma-separated list of one or more of the following events:
  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete
  • A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime error when the trigger is called in bulk from the Lightning Platform​ API.
  • Suppose that you use an after-insert or after-update trigger to change ownership of leads, contacts, or opportunities. If you use the API to change record ownership, or if a Lightning Experience user changes a record’s owner, no email notification is sent. To send email notifications to a record’s new owner, set the triggerUserEmail property in DMLOptions to true.

Note

For example, the following code defines a trigger for the before insert and before update events on the Account object:

1trigger myAccountTrigger on Account (before insert, before update) {
2    // Your code here
3}

The code block of a trigger cannot contain the static keyword. Triggers can only contain keywords applicable to an inner class. In addition, you do not have to manually commit any database changes made by a trigger. If your Apex trigger completes successfully, any database changes are automatically committed. If your Apex trigger does not complete successfully, any changes made to the database are rolled back.