function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
santhosh  konsanthosh kon 

Why can't we perform dml operations in after Triggers

pbattissonpbattisson
The idea is to help avoid recursion. You cannot perform DML on the records which are stored in the trigger context variables. You can however retrieve them using the Ids (or create a new object referring to that record with the same Id ) and then update this. You still have to manage recursion properly though by using a static variable which can be resued over the contexts. For example:
 
Trigger AccountTrigger on Account (after insert) {
 
    if(isAfter() && isInsert()){
        AccountTriggerHelper.performAfterInsert();
    }
}
 
 
public class AccountTriggerHelper {
 
    public static boolean isExecuting = false;
 
    public static void performAfterInsert(){
 
        if( TriggerHelper.isExecuting ){
            // if was executed during the same context 
            // avoid recursion
            return;
        }
 
        TriggerHelper.isExecuting = true; 
        
        //list of new instance of object to update. 
        Account[] accounts = new Account[]{};
      
        for (Account a: Trigger.new) {  
            //here the magic by creating a new instance using the same id
            Account aux  = new Account(Id = a.Id);       
            aux.Name =  a.Id + 'Value forced to be set after by an extrange req';
        }     
        //then update the new instance list. 
        update accounts;
 
    }
 
}

The above code is a slightly tidied up version of the code shared by Martin Bortihiry on his blog (http://devforce.co/apex-tip-how-to-make-a-dml-operation-in-a-trigger-after-insertupdate/) and shows some of the steps you can take to help manage the recursive flow. If you are making updates to records in a trigger you should use the before trigger wherever possible however.