1

I'm using this sample code from Developerforce to avoid recursion in triggers.

public class TriggerMonitor {

    private static boolean run = true;

    public static boolean runOnce() {
        if( run ) {
            run = false;
            return true;
        }
        else {
            return run;
        }
    }

}

I'm looking for ideas on how to adopt this to handle multiple triggers? If I go by this code, I'd have to create a distinct class to handle each trigger and that can get quite messy.

Thanks.

2 Answers 2

1

This is what I have used in the past:

public class TriggerControl {

    public static final String ENTITY_TASK = 'Task';
    public static final String ENTITY_ACCOUNT = 'Account';
    public static final String ENTITY_LEAD = 'Lead';

    @testVisible
    private static Map<String,Boolean> hasRunMap = new Map<String,Boolean>{
        ENTITY_TASK => false,
        ENTITY_ACCOUNT => false,
        ENTITY_LEAD => false

    };

    public static boolean hasRun(String entityType) {

        if (hasRunMap.containsKey(entityType)){
            Boolean hasRun = hasRunMap.get(entityType);
            if (!hasRun) {
                hasRunMap.put(entityType,true);
                return false;
            } else {
                return true;
            }
        }else {
            return false;
        }

    }
}

It uses a map, which means it's quite extensible.

1
  • Thanks to both of you. It is exactly as I had envisioned - just that I couldn't put it down in code. Commented May 26, 2015 at 5:14
1

One class will be enough, but one variable for each object at least. Also don't need to create a method for that, only need to make your variables public and it will do the job. Here is a good example.

    public class TriggerMonitor {

        public static boolean runAccount;
        public static boolean runOpportunity;
        public static boolean runContact;
    }

    trigger AccountTrigger on Account(.....){
        if (TriggerMonitor.runAccount == true) return;
    }

    trigger ContactTrigger on Contact(.....){

        if (TriggerMonitor.runContact == true) return;
        //....blablabla

        TriggerMonitor.runAccount = true;
        update accountList;
        TriggerMonitor.runAccount = false;
    }
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.