Salesforce Trigger:
A trigger is used to done Custom actions or Automation in a programmatic
Way
A trigger is a function or block of code which automatically executes when an
DML Operation Occurs
DML operations - Insert, Update, Delete, Undelete, Merge, Upsert
Enable you to perform custom actions before or after events records
custom actions can be
Sending Email
Field update
Create record
Create Task/Events
Syntax:
trigger triggerName on objectName (trigger_events) {
//Block of code
}
Example
trigger accountTrigger on account (before insert) {
className.MethodName
}
Trigger Events:
Trigger Events is divided in to two one is before Event Another one is After Event.
Each event Include DML operation
Salesforce Trigger: 1
Before Events After Events
Before Insert After Insert
Before Update After Update
Before Delete After Delete
After Undelete
Trigger Context Variables:
Context Variable Definition
Returns true if the trigger was fired due to an insert
Trigger.isInsert
operation.
Returns true if the trigger was fired due to an update
Trigger.isUpdate
operation.
Returns true if the trigger was fired due to a delete
Trigger.isDelete
operation.
Returns true if the trigger is running before any database
Trigger.isBefore
operation.
Returns true if the trigger is running after the database
Trigger.isAfter
operation has completed.
A list of new versions of the sObjects being processed
Trigger.new
(only available in insert and update triggers).
A map of new sObject IDs to their corresponding records
Trigger.newMap
(only available in insert and update triggers).
A list of old versions of the sObjects being processed (only
Trigger.old
available in update and delete triggers).
A map of old sObject IDs to their corresponding records
Trigger.oldMap
(only available in update and delete triggers).
The total number of records being processed by the
Trigger.size
trigger.
Salesforce Trigger: 2
Trigger Events Vs Trigger Context Variables:
Understanding how and when to use these variables is key to writing scalable
and maintainable code.
When have to use Triggers:
Triggers are used in scenarios where flows and process builders cannot meet the
business requirements. Triggers are powerful and can handle complex logic
Complex logic involved
Complex validation required
Automated field updates
Performing DML operation on related records
Handling After undelete events
Call external system
Salesforce Trigger: 3