Recursion in Trigger

By in
128
Recursion in Trigger

In Salesforce, a recursive trigger occurs if the same operation is being invoked again and again. The main reason recursion occurs in the first place is due to the fact that the developer didn’t set a stop condition.

 

How does it occur?

It’s easy to understand it with the help of an example. Let’s assume that an Account record is being inserted. And we have a functionality to clone certain Accounts.

It looks like this.

Account Trigger :

Trigger AccountTrigger on Account(After Insert) {

            if (conditionalstatement) {

                        Insert new Account(Name = ‘some value’);

            }

}

 

The code inserting the Account record looks like this.

Account accRecord = new Account();

accRecord.Name = ‘WGC’;

insert accRecord;

 

Look closely at the above piece of code. First, when an Account is created, the trigger will also try to create a new Account record. Then when that Account is created from the trigger, it will again try to create a new record. This is what causes a recursive trigger in Salesforce.

 

How to stop Recursion?

To stop Recursion, use another class with a Boolean static variable to only run the trigger once no matter what.

That code would be like this.

public class TriggerControl {

            public static Boolean runOnce = true;

}

 

You can use the above class in the trigger that is likely to cause a recursion. The updated Trigger code would look like this.

 

Account Trigger :

Trigger AccountTrigger on Account(After Insert) {

            if(TriggerControl.runOnce == FALSE){

                        TriggerControl.runOnce = TRUE;

            if (conditionalstatement) {

                        Insert new Account(Name = ‘some value’);

            }

}

}

 

After using the above snippet, we always check if the Trigger has run once already and then, immediately set the runOnce value to true.

 

Conclusion

While creating a custom trigger, it’s very important to handle recursion and to run the trigger only once. Because there will be other objects that would perform on Account Object and you don’t necessarily need to run the trigger again and again. As a result, if you take steps ahead of time, you can improve system performance.

 

Additional Resources

Cover Photo by Izabel 🇺🇦 on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *