Monday, June 2, 2014

What is the maximum trigger depth exceeded exception in salesforce?

What is the  maximum trigger depth exceeded exception in salesforce?



When you are creating an Apex code that recursively fires triggers due to insert/update/delete statement for more than 16 times. You will get the Maximum Trigger Depth Exceeded error.

The following example will demonstrate this issue:

trigger cloneAnotherAcc on Account (before insert) {
Account acc = new Account(name=’Clone me’);
insert acc;
}

This trigger will end up in an infinite loop.

In order for you to solve this issue, you can set a condition on insert so it will not be called recursively. Set a flag to manage the insert trigger will be the ideal. To do this, you need to create a new class to keep track the number of times of insert or stop the insert process on second time.

global class triggerCount {
static integer runTimes = 0;

public static integer getRunTimes(){
return runTimes;
}

public static void setRunTimes(){
runTimes++;
}
}

Once you successfully create this class, you can implement this triggerCount class on your trigger to limit the number of times for insert.

trigger createAcc on Account (before insert) {
if(triggerCount.getRunTimes < 2){
Account acc= new Account(name=’Clone me’);
triggerCount.setRunTimes();
insert acc;
}
}



0 comments:

Post a Comment

 
| ,