971
How to avoid recursive trigger execution in Salesforce
Apex Trigger – Apex Trigger is a piece of code that executes Before and After a record is Inserted, Updated, Deleted in a Database.
What is Recursion in Trigger?
Recursion is when same code is executing again and again & it exceeds the “Governor Limit”.
AccountTriggerHandler Helper Class:-
public
Class AccountTriggerHandler{
//Trigger execution check variable
public
static
Boolean runOnce =
true
;
//On before update
public
void
onBeforeUpdate(map<Id, Account> mapNewAccount, map<Id, Account> mapOldAccount){
//Write your logic here
System.debug(
'Is Before Update'
);
}
//On after update
public
void
onAfterUpdate(map<Id, Account> mapNewAccount, map<Id, Account> mapOldAccount){
Update [SELECT Id, Name FROM Account WHERE Id IN: mapNewAccount.keyset()];
AccountTriggerHelper.runOnce =
true
;
System.debug(
'Is After Update'
);
}
}
AccountTrigger in Account Object:-
trigger AccountTrigger on Account(before Update, after Update) {
AccountTriggerHandler handler
=
new
AccountTriggerHandler();
if
(Trigger.isBefore && Trigger.isUpdate && handler.runOnce){
handler
.onBeforeUpdate(Trigger.newMap, Trigger.OldMap);
}
if
(Trigger.isAfter && Trigger.isUpdate && handler.runOnce){
handler
.runOnce =
false
;
handler
.onAfterUpdate(Trigger.newMap, Trigger.OldMap);
}
}
Triggers and Order of Execution – https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm
Reference:
Triggers Basics – https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm
Apex Triggers in Trailhead – https://trailhead.salesforce.com/modules/apex_triggers