Search code examples
salesforceapex-code

Update triggers on 2 objects recursively in salesforce


I have couple of objects(1 custom object called appointment and event object) which i am trying to syncronize. So i have 1 trigger each on each object which searches and updates the records. The issue is, these triggers will keep running recursively as everytime an appointmet is updated the event is also updated and the triggers keep firing and ofcourse salesforce does not accept it.

Any idea how to overcome this?

Thanks


Solution

  • Easiest way is to have an apex class containing a static boolean variable initialised to false. Then in each of your triggers you would check the state of this variable:

    trigger MyTrigger on MyObject (after update)
    {
        if(CStaticTracker.bHasTriggerFired == false)
        {
            CStaticTracker.bHasTriggerFired = true;
    
            // do your work and update the other object here
    
            // shouldn't need this but let's play safe!
            CStaticTracker.bHasTriggerFired = false;
        }
    }
    

    The upshot being, of course, that when one of the triggers runs it'll set this variable to true, and prevent the recursive trigger from executing whatever logic is contained within the if statement. Of course this can still cause some cascading, but it will stop as soon as you don't call another update in one of the triggers.

    Good luck!