Skip to main content Stream TDX Bengaluru on Salesforce+. Start learning the critical skills you need to build and deploy trusted autonomous agents with Agentforce. Register for free.
What is a recursive trigger? What are the best ways to avoid recursive triggers can somebody explain with a simple example.Please help me to understand the concept of recursive triggers.

Thanks
8 Antworten
  1. 5. Aug. 2016, 12:58
    Hi Manish,

    Please find the below explanation 

    What is a Recursive Trigger :

    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.

    How to avoid Recursive Trigger:

    To avoid recursive triggers 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.

    Example:

    Apex 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

    }

    }

    Example2:

    Scenario: There is an after update trigger on account object. In the trigger, there is a date field we are checking the date is changed or not if it is changed we are doing some process.The trigger is executed five times in the transaction.

    ​

    Apex Code:

    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

    }

    }

    For more information refer to the below link

    https://help.salesforce.com/HTViewSolution?id=000199485&language=en_US

    Please mark my solution as the best answer if it helps you.

    Best Regards,

    Nagendra.P
Ladevorgang läuft
0/9000