+ Start a Discussion
SakthidasanSakthidasan 

why we use static variable in recursive trigger

we handle recursive via static boolean variable.but my question is why should we use static boolean variable.instead of object variable(as i understand static is a class variable.we can call directly by class name no object is require) 
Mahesh DMahesh D
How to avoid Recursive trigger

Description: 

Many Developers face this issue because of recursive trigger, or recursive update trigger. For example in 'after update' trigger, Developer is performing update operation and this lead to recursive call.

Resolution:
In order to avoid the situation of recursive call, make sure your trigger is getting executed only one time. To do so, you can create a class with a static boolean variable with default value true.

In the trigger, before executing your code keep a check that the variable is true or not.

Once you check make the variable false.

Class code :
 
public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

Trigger code :
 
trigger updateTrigger on anyObject(after update) {

    if(checkRecursive.runOnce())
    {
    //write your code here            
    }
}
-------------------------------------------------------------------------------------------
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."

Also go through the below links:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm

http://salesforce.stackexchange.com/questions/46790/how-to-avoid-recursive-trigger-other-than-the-classic-class-w-static-variable

http://www.oyecode.com/2012/11/controlling-recursive-triggers-how-to.html

http://www.sfdcpoint.com/salesforce/avoid-recursive-trigger-salesforce/

http://www.infallibletechie.com/2012/08/recursive-triggers-in-salesforce.html

http://www.cloudforce4u.com/2013/07/avoid-recursive-trigger-salesforce.html

http://salesforce.stackexchange.com/questions/24307/how-do-i-control-recursive-triggers-with-static-variables-and-permit-mass-edit-f


Please do let me know if it helps you.

Regards,
Mahesh
Amit Chaudhary 8Amit Chaudhary 8
Problem :-  
1) Many Developers face recursive trigger , or recursive update trigger. For example in 'after update' trigger, Developer is performing update operation and this lead to recursive call.
2) You want to write a trigger that creates a new record ; however, that record may then cause another trigger to fire, which in turn causes another to fire, and so on. 
 
Solution :-
you can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.

 Apex Class with Static Variable
public class ContactTriggerHandler
{
     public static Boolean isFirstTime = true;
}
Trigger Code
trigger ContactTriggers on Contact (after update)
{
    Set<String> accIdSet = new Set<String>(); 
    if(ContactTriggerHandler.isFirstTime)
    {
        ContactTriggerHandler.isFirstTime = false;
         for(Contact conObj : Trigger.New)
  {
            if(conObj.name != 'Test') 
     {
                accIdSet.add(conObj.accountId);
            }
         }
   // any code here
    }
}
Please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_static.htm
2) http://www.sfdcpoint.com/salesforce/avoid-recursive-trigger-salesforce/
3) http://amitsalesforce.blogspot.in/2015/03/how-to-stop-recursive-trigger-in.html

Let us know if this will help you
JyothsnaJyothsna (Salesforce Developers) 
Hi,

Recursion occurs when the same code is executed again and again. It can lead to an infinite loop and which can result in governor limit sometime. Sometime it can also result in unexpected output.

It is very common to have recursion in the trigger which can result in unexpected output or some error. So we should write code in such a way that it does not result to recursion. But sometimes we are left with no choice.
For example, we may come across a situation wherein a trigger we update a field which in result invoke a workflow. The workflow contains one field update on the same object. So trigger will be executed two times. It can lead us to unexpected output.

Another example is our trigger fires on after update, and it updates some related object, and there is one more trigger on a related object which updates child object. So it can result in too infinite loop.

To avoid this kind of situation we can use a public class static variable.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.


In RecursiveTriggerHandler class, we have a static variable which is set to true by default.
public classRecursiveTriggerHandler{
   private static boolean run = true;
    public static boolean runOnce(){
    if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

In the following trigger, we are checking if the static variable is true only then trigger runs. Also, we are setting a static variable to false when trigger runs for the first time. So if the trigger will try to run a second time in the same request, then it will not run.
 
trigger SampleTrigger on Contact (after update){
 
    Set<String> accIdSet = new Set<String>();
     
    if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;
         
        for(Contact conObj : Trigger.New){
            if(conObj.name != 'SFDC'){
                accIdSet.add(conObj.accountId);
            }
        }
         
        // Use accIdSet in some way
    }
}

Please check the below link for more details on Static variables .

https://developer.salesforce.com/forums/?id=906F00000008un1IAA

Hope this helps you!
Best Regards,
Jyothsna
raj_sfdccraj_sfdcc
if we use static variable this will alive for entire tranction .so this scenioro will help us to avoid running more then one time.if you use object variable this will refresh or initilize every time it calls .
Example:
Class:
public class RecursionExampleHandler {

public static Boolean Recursionhandlar=True;
}

Trigger:
trigger RecursionExample on Account (After Insert) {
 
if(Trigger.isAfter&&Trigger.isInsert){
 if(RecursionExampleHandler.Recursionhandlar){
 RecursionExampleHandler.Recursionhandlar=false;
Account acc = new Account(Name = 'Recursive Account');
 
Insert acc;
 system.debug('acccccccccc'+acc);
 }
}
 
}

In the above example if we use Static when trigger calls the calls Variable Recursionhandlar will be true and if trigger calls again that value will be false since trigger changed the value.Since it is static value will be same even it called by trigger number of time.
In case of object variable eventhough trigger changes the variable value when it runs the class value will be again changed to true. So that is the reason we use static variable.

Regards,
Raj.
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)