+ Start a Discussion
Preetham ThummalaPreetham Thummala 

after insert trigger

Can we perform Read/write on "Trigger.new" in after insert?

Hi Preetham Thummala,
its a better approach to use before insert to make any changes to the newly created record, for some reason if you would like to update the record in after insert, you can query the record using something like [SELECT id,name from Object__c WHERE id =: trigger.new] and update your queried record, you cant update trigger.new as it will be read only in after insert.

Fahad Akhtar
Vivek DeshmaneVivek Deshmane
Hi Preetham,
The record is locked because you are catching the record after the insert DML statement has happened. So if you'd like to modify this records (or records), you will need to query anew, modify, then execute another DML statement.

Here is an example of how you could modify your trigger to work:trigger SetProductCategory on OpportunityLineItem (after insert) { List<OpportunityLineItem> olis = [SELECT Id, PricebookEntry.Product2.Product_Category_new__c FROM OpportunityLineItem WHERE Id IN: Trigger.newMap.keySet()]; for (OpportunityLineItem opplineitem: olis){ opplineitem.Product_Category__c= opplineitem.PricebookEntry.Product2.Product_Category_new__c; } update olis; }

Please let me know if it helps you.
Best Regards,