1

I know that after triggers can cause recursiveness. But why are before triggers not recursive?

1
  • Because you are not explicitly mentioning DML in Before triggers
    – gs650x
    Sep 5, 2019 at 10:13

1 Answer 1

1

It's not just after triggers that can be a problem, any trigger can have problems with recursion, though some are more likely than others to experience that problem.

Update triggers are the most likely to have recursion issues (especially after update), but Insert triggers can pretty easily be set up to recurse infinitely too.

I suppose that even Delete and Undelete triggers could have recursion issues, though I think that'd be harder to pull off under normal circumstances (you'd need to put some effort into making that happen).

gs650x's suggestion that not needing explicit DML is part of the equation here. If you edit an instance of an object contained in Trigger.new or Trigger.newMap in a before insert or before update trigger, no dml is required to persist those changes. This makes it less likely that a before trigger will cause issues with recursion.

It is still possible, however. Consider the following:

trigger BeforeRecursion on Account (before insert){
    List<Account> newAccounts = new List<Account>();

    for(Account acct :trigger.new){
        newAccounts.add(new Account(
            Name = acct.Name
        );
    }

    insert newAccounts;
}

While you're not operating on the same Account every time, this example trigger will recurse infinitely (well, it would, but Salesforce should put a stop to it after the 16th iteration or so).

The rule of thumb to determine if a trigger is going to have issues with uninhibited recursion is this: As part of executing this trigger, and any other code that is run because of it, do I perform the same DML as what my trigger handles?

If you insert accounts in a before insert trigger on Account, you're probably going to have issues.

This goes deeper than that though. If, at any point in a transaction after you run a specific trigger, you happen to perform DML on the same object, you can have recursion issues.

Not the answer you're looking for? Browse other questions tagged .