I have Object Alpha and Object Num with fields A,B,C and 1,2,3 respectively.
I have to write trigger on both objects
- when field A on Object Alpha is updated, field 1 on Object Num should be updated and vise versa.
- Similarly when field B on Object Alpha is update, field 2 on Object Num should be updated and vise versa.
- Similarly when field c on Object Alpha is updated, field 1 on Object Num should be updated and vise versa.
How to should avoid recursive triggering (when field A updates field 1 then trigger on Object Num is not triggered to update field A on Object Alpha that again triggers a field update …. ) Any inputs?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Recursion guards are very tricky. Using a simple static Boolean is a bad practice: there are lots of reasons for your trigger to be fired more than once in a transaction, and using a runOnce
-style Boolean will mean your trigger just silently does nothing in those cases. This often produces difficult to debug behavior.
Instead, use static Booleans that are scoped to a single DML statement, like this.
class TriggerContext { static Boolean isUpdatingOtherObject = false; } trigger SomeTrigger on Object_A__c (after update) { if (!TriggerContext.isUpdatingOtherObject) { TriggerContext.isUpdatingOtherObject = true; update [SELECT Id FROM Object_B__c ...]; TriggerContext.isUpdatingOtherObject = false; } } trigger AnotherTrigger on Object_B__c (after update) { if (!TriggerContext.isUpdatingOtherObject) { TriggerContext.isUpdatingOtherObject = true; update [SELECT Id FROM Object_A__c ...]; TriggerContext.isUpdatingOtherObject = false; } }
Note that the recursion guard is active only during the DML operation against the other object in the pair. This ensures that both triggers fire exactly when they need to, but don’t fire in response to one another’s updates.
Method 2
you can create a helper like this
public class ContactTriggerHelper {public static Boolean runOnce = true; public static void onAfterUpdate(List<Contact> newacc){ for(Integer i=0;i<newacc.size();i++) { insert (new Account(Name='Test'+i)); runOnce = true; System.debug('Is After Update'); }} }
and then in trigger you can check
if(Trigger.isAfter && ContactTriggerHelper.runOnce){ ContactTriggerHelper.runOnce = false; ContactTriggerHelper.onAfterUpdate(Trigger.New); }
create same for other objects too
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0