Sub topic 9
After triggers and related-record DML
This chapter assumes you know basic Apex syntax, collections, DML statements, SOQL, and governor limits. You should also know that a before trigger runs before a record is saved and an after trigger runs after it is saved.
What changes after the save
In an after trigger, the database has already written the record. Two things follow from that:
- Every record has an
Id. This is the main reason to use an after trigger: you can point related records at a new parent. - The records in
Trigger.neware read-only. Assigning a value to a field on them throws aSystem.FinalException. To change the triggering records, query or construct separate copies and update those.
The changes are still not permanent. If a later step in the transaction throws an unhandled exception, Salesforce rolls back everything, including the saved record.
Creating related records
This trigger creates a follow-up task for each new account. It uses a.Id, which does not exist in a before insert trigger.
trigger AccountFollowUp on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up with new account',
WhatId = a.Id
));
}
insert tasks;
}The loop only builds the list. The single insert tasks; runs once after the loop, so a batch of 200 accounts uses one DML statement, not 200.
Updating other records
Suppose you want to stamp a field on each account's contacts. You can't write to Trigger.new, but you can query other records and update them. Do the query once, outside the loop.
trigger AccountContactSync on Account (after update) {
List<Contact> toUpdate = new List<Contact>();
for (Contact c : [
SELECT Id, Description, AccountId
FROM Contact
WHERE AccountId IN :Trigger.newMap.keySet()
]) {
c.Description = 'Parent account updated';
toUpdate.add(c);
}
update toUpdate;
}Trigger.newMap.keySet() supplies the account Ids for the IN clause. This works in after update, where newMap is available.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `FinalException: Record is read-only` | Assigning a field on `Trigger.new` in an after trigger | Move the change to a before trigger, or update a separate copy of the record |
| `WhatId` or lookup is null | The related record was created in a before insert trigger, where `Id` is null | Use after insert |
| `Too many DML statements: 151` | `insert` or `update` inside the loop | Collect records in a list and run DML once |
| Trigger fires repeatedly | Your DML updates the object that owns the trigger | Add a static guard, covered in a later chapter |
Choosing before or after
Use a before trigger to change the triggering record's own fields, because the change is saved without any DML. Use an after trigger when you need the record's Id, or when you change other records.
Exercise
A trigger on Opportunity must create a Task for each new opportunity, with the Task's WhatId set to the opportunity. Which event do you use, and why can't you use before insert?
Show answer
Use after insert. In before insert the opportunity has no Id yet, so WhatId can't be set. Build the Tasks in a list inside the loop and insert the list once after the loop.
Exercise
An after update trigger runs a.Description = 'Updated'; on a record from Trigger.new. What happens, and how do you fix it?
Show answer
It throws a FinalException because Trigger.new records are read-only in after triggers. Change the trigger to a before update trigger so the assignment is saved without DML, or query a fresh copy of the record and update that.