Types of Apex Triggers
1. Before Triggers
These are used to update/modify or validate records before they are saved to database.
2. After Triggers
These are used to access fields values that are set by the system like recordId, lastModifiedDate field. Also, we can make changes to other records in the after trigger but not on the record which initiated/triggered the execution of after trigger because the records that fire the after trigger are read-only.
Syntax & Trigger Events
trigger TriggerName on ObjectName(trigger_events) {
//code-block
}
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
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 c = new Contact(LastName = 'Steve');
insert c;
}
trigger ApexTrigger on Contact(after insert) {
Account a = [SELECT Name FROM Account LIMIT 1];
a.Name = 'Updated Account';
MyException me = new MyException();
throw me;
// update a; // Not Allowed
}
Triggers can modify other records of the same type as the records that initially fired the trigger.
As triggers can cause other records to change and because these changes can, in turn, fire more triggers, the apex runtime engine considers all such operations a single unit of work & sets limits on the number of operations that can be performed to prevent infinite recursion.
