Sub topic 9
After Triggers and Related-Record DML
This chapter assumes you can write basic Apex (loops, List, Set, Map), you know what DML statements and SOQL queries are, and you know the main governor limits. It covers what an after trigger can and cannot do, and how to create or update related records from one safely.
What changes after the save
A before trigger runs before Salesforce writes the record to the database. An after trigger runs once the record is saved in the transaction, though the transaction is not yet committed. Three facts follow from this.
- Records new to the database have an
Id. Inafter insert,Trigger.newcontains Ids, andTrigger.newMapis available. Inbefore insertneither has Ids. - Values calculated by the system, such as
CreatedDateand formula fields, are populated. - The records in
Trigger.neware read-only. Assigning a field value throws aSystem.FinalException.
trigger AccountReadOnlyDemo on Account (after insert) {
for (Account a : Trigger.new) {
a.Description = 'Too late'; // FinalException: Record is read-only
}
}If you need to change the record that fired the trigger, you have two options. Move the logic to a before trigger, which is the better choice when it is possible. Or query a fresh copy of the record in the after trigger and update that copy with DML. The second option saves the record again and fires the update triggers again, so it costs more.
Creating related records
The most common use of an after trigger is creating child or related records. The parent Id is needed for a lookup or master-detail field, and only the after event guarantees it exists on insert.
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 runs once after the loop, so 200 accounts cost one DML statement and not 200. The limit is 150 DML statements per transaction, so a DML statement inside the loop fails on a batch of 151 or more records.
An empty list is safe to insert. Apex does not count insert on an empty list against the DML row limit, although it still counts as a statement. To save a statement, you can check if (!tasks.isEmpty()) first.
Updating other records
You can also update related records. The usual pattern is to collect the parent Ids, query once, change the values and update once.
trigger ContactCountSync on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
if (accountIds.isEmpty()) {
return;
}
List<Account> toUpdate = new List<Account>();
for (Account a : [
SELECT Id, Description FROM Account WHERE Id IN :accountIds
]) {
a.Description = 'Has contacts';
toUpdate.add(a);
}
update toUpdate;
}Here the Account records come from the query, not from Trigger.new, so they are writable. The Set removes duplicate Ids when several contacts share one account. The query uses IN :accountIds, so it is one SOQL statement for the whole batch.
Using the old values in after update
After update triggers still have Trigger.old and Trigger.oldMap, so you can run follow-up work only when something changed.
trigger OpportunityWonTask on Opportunity (after update) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName == 'Closed Won' && oldOpp.StageName != 'Closed Won') {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}Comparing the new and old stage means the task is created once, on the transition, not on every later save of an already-won opportunity.
Rejecting records from an after trigger
addError works in after triggers too. It rolls back the whole transaction, including the record that was just saved and any DML your trigger already ran. The difference from a before trigger is the cost: the save work has already been done and is then discarded. Prefer a before trigger for validation that depends only on the record itself. Use an after trigger when the check needs data that exists only after the save, such as a count of related records.
trigger ContactLimit on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acc, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acc'), (Integer) ar.get('total'));
}
for (Contact c : Trigger.new) {
Integer total = counts.get(c.AccountId);
if (total != null && total > 10) {
c.addError('An account can have at most 10 contacts.');
}
}
}The query runs after the new contacts are saved in the transaction, so the count includes them.
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 queried copy |
| `Too many DML statements: 151` | `insert` or `update` inside a loop | Collect records in a list, run one DML statement after the loop |
| `Too many SOQL queries: 101` | Query inside a loop | Collect Ids in a `Set`, query once with `IN :ids` |
| `Id` is null on a new record | Reading `Id` in `before insert` | Create the related record in `after insert` |
| Trigger runs repeatedly or hits a depth limit | The trigger's own DML on the same object fires it again | Add a guard or avoid updating the same object (see the recursion chapter) |
Edge cases
- Same-object DML. Updating records of the object that fired the trigger runs that object's triggers again. A queried account update inside an
Accountafter trigger can start a loop. A static guard stops it. The depth limit is 16 nested trigger levels. - Partial failure. A plain
insertis all-or-nothing. If one related record fails, the exception rolls back the whole transaction, including the saved triggering records.Database.insert(list, false)allows partial success. You must then inspect the returnedDatabase.SaveResultobjects, because errors are not thrown. - Failures on related records. To report a failure against the triggering record, catch the
DmlExceptionand calladdErroron the matching record inTrigger.new. This is allowed in an after trigger. - Mixed DML. Setup objects such as
Usercannot be changed in the same transaction as non-setup objects likeAccount. Move the setup-object work to asynchronous Apex. - Roll-ups. An after trigger that totals child records onto a parent should also handle
after delete(usingTrigger.old) andafter undelete, or the total goes stale.
Exercise
An after insert trigger on Contact sets c.Description = 'New' for each contact in Trigger.new, and the save fails with a read-only error. Give two ways to fix it and say which one you would choose.
Show answer
Change the event to before insert and keep the assignment, because before triggers may edit Trigger.new and no DML is needed. Or, in the after trigger, query the contacts by Id into a new list, set the field on the queried copies and call update once. This saves the records a second time and re-fires update triggers. Choose the before trigger, because it is cheaper and does not cause extra trigger runs.
Exercise
A trigger on Opportunity (after update) creates a Task for every opportunity in Trigger.new by calling insert inside the loop. It works in the UI but fails in a data load of 200 records. What is wrong and how do you fix it?
Show answer
Each loop iteration runs a DML statement, and a transaction allows only 150. A single record in the UI stays under the limit, but a batch of 200 does not. Build a List<Task> inside the loop and run one insert after it.