Types of Apex Triggers in Salesforce
Chapter Topics
- Basics of Triggers
- When to use triggers
- Types of Apex Triggers in Salesforce
- Trigger Order of Execution
- Trigger Context Variables in Salesforce
- Trigger.new in Salesforce| Context Variables in Apex Triggers
- Trigger.old in Salesforce | Context Variables in Apex Triggers
- Trigger.newMap in Salesforce| Context Variables in Apex Triggers
- Trigger.oldMap in Salesforce| Context Variables in Apex Triggers
- Trigger Exceptions
- Best Practice in Triggers
- Trigger Helper Class Pattern
Apex Triggers in Salesforce are used to invoke various Apex code actions. They allow the user to perform custom actions before or after the new records or changed records saved to the database. It triggers on record cChanges such as insertions, updates, or deletions.
A trigger in Apex code can be executed before or after the following types of operations:
- insert
- update
- delete
- merge
- upsert
- undelete
Types of Triggers in Salesforce
There are two types of Triggers in Salesforce:
- Before Triggers: These triggers are used to update or validate triggering record values before they’re saved to the database.
- After Triggers: These are used to access fields values that are already set by the system like recordId, lastModifiedDate field for performing after save actions like sending mail. After Triggers are also used to make changes to other records. However, they cannot be used on the record which initiated/triggered the execution of after trigger because the records that fire the after trigger are read-only.
Apex Trigger Syntax
trigger TriggerName on ObjectName(trigger_events) { //code-block } |
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.’); } |
Note:
If you update or delete a record in its before trigger, or delete a record in its after trigger you’ll receive an error and this includes 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 } |
Trigger Events in Salesforce
Here is a list of trigger events in Salesforce.
Next TopicNeed more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.