[SalesForce] How to prevent a trigger firing during a batch job

I have a batch job that updates accounts. There is also an after trigger (just to make life more complicated).

I want that the trigger will not fire during the batch job.

I wrote a global validator class, and trying to control run's with it.

global class Validator_CLS{
    private static boolean blnAlreadyDone = false;

    public static boolean hasAlreadyDone(){ return blnAlreadyDone; }
    public static void setAlreadyDone() { blnAlreadyDone = true; }   
}

Batch works: calls the global class – sets parameter to true

Batch:

public class SF2NSUpdateOpportunityNSId{

    public static void collectData(){

        if(Validator_cls.hasAlreadyDone())
        {
            system.debug('no need to run again');
            return ; 
        }
...... Alot more code here

When trigger fires, it needs to NOT run if parameter is true.

Trigger:

trigger trgSF2NSAccount on Account (after update,after insert) {

    system.debug('trgSF2NSAccount + Validator_cls.hasAlreadyDone ' + Validator_cls.hasAlreadyDone());
    if(Validator_cls.hasAlreadyDone())
    {
        system.debug('no need to run again');
        return ; 
    }
.... A LOT more code here as well

Something is wrong.

The trigger keeps firing

Best Answer

You can use !system.isBatch() in your trigger to check if it is fired from within a batch or not

Related Topic