Wednesday 4 March 2015

TRIGGER RECURSION IN SALESFORCE

How to avoid Trigger Recursion in salesforce


If an executing trigger calls itself then it goes to into infinite loop and is called recursion.
Use Case
trigger DemoTrigger on Demo__c (before insert) {
insert new Demo__c();
}
In the above example when try to insert a record in trigger again Trigger will invoke(Because when try to insert a record again trigger will invoke) until trigger limit exceeded

If a trigger on a particular object executing on a particular DML does the same DML on that object then the same trigger would be called and it will go into recursion.
A static variable can be set in a class before executing the trigger to avoid the recursion.
Solution 

Class:
public class p { 
  public static boolean firstRun = true; 
}
Trigger:
trigger TestTrigger on Demo__c (before insert) {
if(p.firstRun)
{
p.firstRun = false;
insert new Demo__c();
}    
}

No comments:

Post a Comment