function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
How to convert S-Control to VFHow to convert S-Control to VF 

what is Recursive trigger & how to avoid it?

Pls explain me what is Recursive Trigger & how to avoid Recursive problem?

Ritesh AswaneyRitesh Aswaney

A recursive trigger is one that performs an action, such as an update or insert, which invokes itself owing to,  say something like an update it performs.

 

eg in a before trigger, if you select some records and update them, the trigger will invoke itself.

 

To avoid, static variable 'locks' are used. Illustrated in the salesforce doc

 

"Static variables are only static within the scope of the request. They are not static across the server, or across the entire organization.

Use static variables to store information that is shared within the confines of the class. All instances of the same class share a single copy of the static variables. For example, all triggers that are spawned by the same request can communicate with each other by viewing and updating static variables in a related class. A recursive trigger might use the value of a class variable to determine when to exit the recursion."

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_static.htm

Sunil Joshi 3Sunil Joshi 3
If we perform update operation on the record in after update event logic recursive triggers will arise.
Using static boolean variable in an apex class (we should not keep static boolean variable inside of the trigger) we can avoid recursive triggers.
Ajinkya DhasAjinkya Dhas

Recursive Trigger
When you want to write a trigger that creates a new record as part of its processing logic. However, that record may then cause another trigger to fire, which in turn causes another to fire, and so on. You don't know how to stop that recursion.

Using a static variable in an Apex class to avoid an infinite loop. A static variable is local to the context of a web request (or test method during a call to runTest()), so all triggers that fire as a result of a user's action which has access to it.

Let's understand some scenarios...

Scenario :
Suppose there is a scenario where one trigger perform an update operation, which results in invocation of the second trigger and the update operation in second triggers acts as triggering criteria for triggers one.

Apex Class :
============================================
public class utility
{
 public static boolean isFutureUpdate;
}

============================================

Apex Class 2 :
============================================
public class FutureMethods
{
  @future
 public static void processLargeAccounts(set<Id> accIds)
 {
  List<Account> accToUpdate = new List<Account>();

/* isFutureUpdate is set to turn to avoid recurssion */
  utility.isFutureUpdate = true;
  update accToUpdate;
 }
}

============================================

Trigger :
============================================
trigger updateSomething on Account(after insert, after update)
{
 
/*This trigger performs its logic when the call is not from @future*/
 if(utility.isFutureUpdate != true)
    {
        set<Id> idsToProcess = new Set<Id>();
        for(Account acc : trigger.new)
        {
            if(acc.NumberofEmployers > 500)
            {
                 idsToprocess.add(acc.Id);                    
            }
        }
     
  /* Sending Ids to @future method for processing*/
        FutureMethods.processLargeAccounts(idsToprocess);
    }
  }

============================================

In the above scenario, it will first check utility.isFutureUpdate != true from utility class. If it is false that means, a call is not from the future method then it will perform its logic.

Then it will send its Ids to the FutureMethods class to process further.

For more scenarios and error problems please visit :
https://www.salesforcekid.com/2019/07/recursive-triggers-in-salesforce.html

I hope this will help you to solve your problem.
HAPPY LEARNING ☁️⚡️

AJINKYA DHAS ☁️⚡️
Salesforcekid (http://www.salesforcekid.com
raj_sfdccraj_sfdcc
Hi,
In general Recursion is executing the same task repeatedly. The Recursive trigger occurs when same trigger called it self multiple times which results in infinite loop. Which would throw an error without commiting the changes to database.

Please find the below link with full explanation with example :

Recursive Trigger (https://salessforcehacks.blogspot.com/2019/12/salesforce-recursive-triggers-fully.html)
{tushar-sharma}{tushar-sharma}
Hi,
We have multiple ways to avoid recursive triggers. They all depend on your use case, While one solution may work but will not work for others. Check the below links, It has multiple ways to avoid recursive trigger: https://newstechnologystuff.com/2020/05/28/avoid-recursive-trigger-in-salesforce/
manu manu 23manu manu 23
Hi,
Recursive triggers happen when the trigger by itself excute infinite times due to the code that's been written 
EXAMPLE: 
trigger class trigger Accounttrigger on account(after insert) {    
   if(Trigger.isAfter&&Trigger.isInsert){     
       Account acc = new Account(Name = 'Recursive Account');                   
       Insert acc;  }  }



If you look at the above code, there is a trigger on account object. 
The trigger gets fired when the account is inserted(after) 
In the same code i want another account to be createed, Which means another account is inserted. 
The second record after getting inserted, the trigger runs again and the another record is created......this goes on untill system throws an maximum depth exception. 

How to avoid this loop over the trigger? Please look at the code below 

//after adding the static varibale to the trigger 
trigger class trigger Accounttrigger on account(after insert) {       if(Trigger.isAfter&&Trigger.isInsert && recursion.isfirst){      
       recursion.isfirst=false;             
       Account acc = new Account(Name = 'Recursive Account');            
       Insert acc;  }  }

 //recursion class 

public class recursion{ 
 public static boolean isfirst=true; 
​​​​​​​ }


If you look at the above the code there is a slight change as i have added another condition to execute the trigger. The trigger gets executed if all the conditions gets executed. 
The condition is (if account is after insert and static variable is true)

step1. The system runs the trigger when you create an account 

step2. The system checks if the static variable is true 

step3. As in the recursion class, i created a static variable called isfirst and set it as true. so for the first time, when the account is created the static varible is true 

step4. So it goes in to the if condition because the static variable is true 

step5. updates the static varible to false...//because, if it runs for the second time, the static varible (recursion.isfirst) should become flase so that the if condition doesn't run again 

step6. creates an account (name=Recursive Account)

step7. As per the trigger, after the account getting inserted, the trigger again goes back to the if condition and checks if condition satisfies, now, as i already told you, the if condition doesnt satisfy as the recursion.isfirst value becomes false as it's been updated to false when the first time account got created.

step8. now the trigger doesn't run for the second time as the condition didnot satisfy 

​​​​​​​
step9. insert the account that's been given in the code