How to write simple after update trigger on Account Object?

  • I am writing a trigger that's supposed to be calculating the NPS Score, but can't even seem to update the Account by writing a value to a field. I keep getting this error:

    execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 001f000000BdVpzAAF; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

    trigger CalculateNPS on Account (after update) {
        List<Account> acc = new List<Account>();
        acc = [SELECT Id FROM Account WHERE Id IN: Trigger.oldMap.keySet() LIMIT 1];
    
        for (Account a : acc) {
            a.NPS_Score_Trigger__c = 9;
        }
       update acc; 
    }
    
  • Jason Clark

    Jason Clark Correct answer

    7 years ago

    This should be a Before Update trigger. Consider what would happen if your trigger worked - the last statement updates account - firing the update trigger again, which will update account... ad infinitum. While you can use a static variable in a helper class to prevent cascading triggers, that isn't needed here.

    In most cases, you should use a before trigger to validate pending changes (in case the validation fails, you can prevent the change before it is committed), and to make additional changes to the triggering object, and you should use an after trigger to make changes to other objects. Here's how I'd re-write your trigger, based on the code you provided:

    trigger CalculateNPS on Account (before update) {
        for (Account updatedAccount : Trigger.new) {
            updatedAccount.NPS_Score_Trigger__c = 9;
        }
    }
    

    Notice also that I did not call update in the before trigger - any changes made to Trigger.new will be included as part of the pending update that trigged the code.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used