Posts Tagged ‘Recursive trigger pattern’

In salesforce, i think people easily come around governance limit. And in our scenario, we were working and we were able to see that, one trigger updating same record, so after trigger called, and by this, same trigger was called 5 times, which was causing 72 soql executing part of transaction and warning alarmed. And solution to this is static.

As a Core Java Dev, i got confused static, but static in java is across class loader, and here in salesforce on transaction, so that resolves the problem.

Create one static boolean flag variable in class and update when trigger is called first time, So from next time always this flag variable is always false. And with that trigger will not run again for same Transaction.
Alternative 1:

Class code :
class CaseTriggerFlag {
private static boolean caseTriggerRunFlag=true;
public static boolean runOnce(){
if(caseTriggerRunFlag) {
caseTriggerRunFlag=false;
return true;
}else {
return caseTriggerRunFlag;
}
}
}

Trigger code :
trigger CaseTrigger on Case (after update) {
if(CaseTriggerFlag.runOnce()){
/** YOUR CODE COMES HERE
*/
}
}

Alternative 2:

Class code :
class CaseTriggerFlag {
public static boolean caseTriggerRunFlag=true;
}

Trigger code :
trigger CaseTrigger on Case (after update) {
if(CaseTriggerFlag.caseTriggerRunFlag){
CaseTriggerFlag.caseTriggerRunFlag=false;
/** YOUR CODE COMES HERE
*/
}
}