What is Recursive Trigger in Salesforce?
Recursive Trigger is a trigger which is called and called itself when some DML operation occurs. Recursion basically occurs when we perform same dml in the apex trigger method (ex: If we perform update operation in update triggers). Recursion occurs when the trigger code called itself in a infinite loop until system throws error “maximum trigger depth exceeded”.Salesforce Recursive Trigger Simple Example:
Trigger t1 on Contact(after insert){
Insert new Contact(Lastname=’Venu’, Phone=12345);
}
In above trigger, when we inserts new contact record , then the trigger t1 called, as per trigger logic new contact record should be created and that new record calls again this trigger as it is after insert trigger and again new record inserted it will be goes on in a loop until system stops. Finally we will get error “maximum trigger depth exceeded” Like Below.
How To Avoid Recursive Trigger in Salesforce?
To avoid Recursive Trigger problem we have to create a public class with static Boolean variable as below.class:
public class AvoidRecursive {
public static boolean firstRun = true;
}
Trigger:
trigger TestTrigger on Contact (after insert) {
if(AvoidRecursive.firstRun)
{
AvoidRecursive.firstRun = false;
insert new Contact(Lastname=’Venu’, Phone=12345);
}
}
Here first time we set Boolean variable as “TRUE” in class . In trigger variable is equals to true then it goes to inside loop, performs logic and then variable sets as “FALSE” so next time it will not run(if variable=false then it will not goes to loop & will not perform logic). So if Code will try to run second time in same request then it will not run.
No Comment to " What is Recursive Trigger in Salesforce? How can we Avoid Recursive Trigger in Salesfore with Example "