Apex Triggers in Salesforce are utilized to execute various Apex code actions. They enable users to perform custom operations before or after new or modified records are saved to the database. Triggers are activated by record changes, such as insertions, updates, or deletions.
In Apex, a trigger can be executed either before or after the following types of operations:
- insert
- update
- delete
- merge
- upsert
- undelete
Categories of Triggers in Salesforce
Before Triggers: These are used to modify or validate the values of the triggering record before it is saved to the database.
After Triggers: These triggers allow access to field values already set by the system, such as recordId
or lastModifiedDate
, for performing post-save actions like sending emails. They can also be used to modify other records. However, they cannot make changes to the record that initiated the trigger, as those records are read-only once the after trigger is fired.
Apex Trigger Structure
trigger TriggerName on ObjectName(trigger_events) { //code-block }
Sample Example
trigger FirstTrigger on Account(before insert) { System.debug(‘I am before insert.’); } Trigger SecondTrigger on Account(after insert) { System.debug(‘I am after insert.’); }
Important Note:
Attempting to update or delete a record within its own before trigger, or deleting a record within its after trigger, will result in an error. This applies to both direct and indirect operations.
trigger ApexTrigger on Account(before update) { Contact contactRecord = new Contact(LastName = ‘Steve’); insert contactRecord } trigger ApexTrigger on Contact(after insert) { Account accountRecord = [SELECT Name FROM Account LIMIT 1]; accountRecord.Name = ‘Updated Account’; MyException myExceptionObj= new MyException(); throw myExceptionObj; // update accountRecord; // Not Allowed }
Salesforce Trigger Events
Below is a list of trigger events in Salesforce: