Tuesday, December 22, 2015

Recursive trigger in salesforce and how to avoid it?

Recursion occurs when the code gets called again and again and goes into a infinite loop. It is always advisable to write a code that does not call itself. However, sometimes we are left with no choice. Recursion occurs in trigger if your trigger has a same DML statement and the same dml condition is used in trigger firing condition on the same object(on which trigger has been written)
For example, if your trigger fires on after update on contact and you update any contact record in your trigger then the same trigger will be called and will lead to a infinite loop.
To avoid this kind of recursion and call the trigger only once we can use global class static variable.
As an example let says you have following trigger on contact:
trigger recursiveTrigger on Contact (after update) {
Id recordId ;
 for(contact con : trigger.new){
     recordId = con.id; 
 }
 Contact conRec =[select id,name,email from contact where id !=: recordId limit 1];

 conRec.email = 'test@test.com';
 update conRec;
 }
}
As you can see the trigger is getting called on after update and as the trigger has a DML update statement on the same object, same trigger will be called again leading to recursion.
To avoid this, just create one global class with a static global boolean variable as below.
global Class recusrssionPreventController{
Global static boolean flag = true;
 Public recusrssionPreventController(){
 }
}
And set this boolean variable in your trigger and then set this boolean variable to false as done in the trigger below
trigger recursiveTrigger on Contact (after update) {
Id recordId ;
if(recusrssivePreventController.flag == true){
   recusrssivePreventController.flag = false;
 for(contact con : trigger.new){
     recordId = con.id; 
 }
 Contact conRec =[select id,name,email from contact where id !=: recordId limit 1];

 conRec.email = 'test@test.com';
 update conRec;
 }
}
This will call the trigger only once and hence avoid recursion.

No comments:

Post a Comment