Activity Forums Salesforce® Discussions Trigger in salesforce

  • Anurag

    Member
    August 30, 2018 at 1:35 pm

    Hi Madhulika,

    You need to add one Static Boolean variable to a your utility/helper class (any apex class), and check its value within affected triggers, where you do think this trigger will get fired more than once.

    "MyUtilityClass" is your helper  / utility apex class  where we will have our static boolean variable - e.g. declared as "runOnceFlag= true"

    public class MyUtilityClass {
       public static boolean  runOnceFlag= true;
    }

    Sample example Trigger - where you will check for the value of static boolean variable "runOnceFlag"- For first time its value will be equal to TRUE, and we will set its value to FALSE in our trigger to avoid second run.

    trigger myTriggerName on Account (before delete, after delete) {
        
         if(Trigger.isBefore && Trigger.isDelete){
       
             if(MyUtilityClass.runOnceFlag){
                    MyUtilityClass.runOnceFlag=false;           }
        }
    }

  • shariq

    Member
    September 17, 2018 at 9:48 pm

    Hi,

    Try this -

    Class code 
    public class checkRecursive {
         public static Set<Id> SetOfIDs = new Set<Id>();
    }

    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 Set

    Check if the record exists in the set, if so do not execute the trigger, else execute the trigger.

    NOTE: Before deploying into production, we recommend testing in sandbox.

    This is a sample code written for Account object Class code
    public class checkRecursive {
    public static Set<Id> SetOfIDs = new Set<Id>();
    }
    Trigger code 
    trigger TestTrigger on Account (before insert) {
        if (Trigger.isAfter && Trigger.isInsert) {
            List<Account> accList = new List<Account>();
          for (Account test: Trigger.new) {
              If(!checkRecursive.SetOfIDs.contains(test.Id)){
                  test.Name = 'helloworld'; 
                  accList.add(test);
                checkRecursive.SetOfIDs.add(test.Id);
              }
          }
          insert  accList;
        }
    }

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos