Sharing My IT Experience

Avoid Recursive Trigger Calls In Salesforce

Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime. Sometime it can also result in unexpected output or the error “maximum trigger depth exceeded”. So, we should write code in such a way that it does not result to recursion.

For example, I’ve a trigger on Account object, which will be execute on before Update and after Update. In after Update I’ve some custom logic to update Account records. So, when I’m updating the Account records in After Update, it is throwing error “maximum trigger depth exceeded”. So, it is a recursion in apex trigger.

To avoid the situation of recursive call, we have to write code in such a way that the trigger will execute one time. To do so, we can create a class with a static Boolean variable with default value true. In the trigger, before executing the code keep a check that the variable is true or not.

Here in below trigger, I want to execute both before and after Update trigger only one time. I’m checking the static Boolean variable is true in both before and after Update trigger. In after update trigger changed the variable to false and after updating the account records, again changed the variable to true. In this way you can handle bulk of records in recursive trigger.