Apex Triggers come into the picture when point and click or Admin Level configurations do not suffice the requirements of the end-user in Salesforce. For any custom logic that we want to be processed or implemented whenever a record goes through CRUD operations, Apex Triggers are responsible for taking care of this logic.
Types of Events:
- before insert
- after insert
- before update
- after update
- before delete
- after delete
- after undelete
Each event has two type of actions: before and after
Only undelete event doesn't have a before action to it.
If we want to make any changes to the records which are being inserted/updated/deleted, we make those changes in the before trigger whereas if we want to update some related records based on the current records, we make those changes through the after the trigger.
Context variables in Triggers:
To access the run-time context, Triggers provide us with context variables that can be accessed and used. These variables are:
Recursive Triggers: Is it possible to have one?
Yes, there could be cases when the trigger ends up calling the trigger again running in a loop. To avoid such scenarios, best practices suggest using a static variable, add a check on the code to determine if the trigger is called for the first time or not, and call trigger logic only once.