Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer
    
Thanks to both of you. It is exactly as I had envisioned - just that I couldn't put it down in code. –  miCRoSCoPiC_eaRthLinG May 26 at 5:14

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;
    }
share|improve this answer
    
Thank you very much. Both code samples are a big help! –  miCRoSCoPiC_eaRthLinG May 26 at 5:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.