Development questions
Why are records in Trigger.new read-only in after triggers?
In after triggers the records have already been written to the database (not yet committed), so the save operation is complete. Modifying Trigger.new fields would have no effect on what was saved, and Salesforce throws Record is read-only.
To change the same record in an after trigger, query a fresh copy (or create a new SObject instance with the Id) and perform DML on it. This re-fires triggers, so guard against recursion. Better, move same-record logic to a before trigger.
apex-triggertriggerdml
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?