Sub topic 9
After triggers: using the Id and touching related records
This chapter assumes you can write a basic Apex trigger, know what Trigger.new and Trigger.old hold, and understand DML (insert, update, delete). You should also know that a record save runs inside one transaction. Earlier chapters covered before triggers and custom validation. This chapter covers what changes once the record has been written to the database.
Where after triggers run
An after trigger runs once the platform has saved the record to the database. The save is not committed yet. The record has a real row, an Id, and system-populated values. The transaction can still roll back.
Validation has already passed by this point. Your after trigger therefore sees data that the platform accepted. If your code throws an error, though, every change made so far in the transaction is undone.
Why the Id is available
In before insert, the record does not exist in the database, so Id is null. In after insert, the row exists and Trigger.new records carry their Ids. The same applies to system fields such as CreatedDate, LastModifiedDate, and formula fields, which are calculated from saved values.
This is the main reason to choose an after trigger. Use one whenever you must point another record at the new record.
trigger AccountFollowUp on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(Subject = 'Follow up', WhatId = a.Id));
}
insert tasks;
}The trigger builds every task in a loop and runs one insert after the loop. This is the bulk-safe pattern. A single save can contain up to 200 records, and a DML statement inside the loop would use one of your 150 DML statements per record.
Trigger.new is read-only in after triggers
In a before trigger, you can assign to fields on Trigger.new and the platform saves them without DML. In an after trigger, the records are read-only. Writing to a field throws a System.FinalException (the message says the record is read-only).
trigger AccountBadAfter on Account (after insert) {
for (Account a : Trigger.new) {
a.Description = 'Too late'; // FinalException: Record is read-only
}
}The record is already saved, so the platform no longer treats that in-memory copy as the thing to write. To change the same record from an after trigger, query or construct a separate sObject with the same Id and update it.
trigger AccountAfterEdit on Account (after insert) {
List<Account> updates = new List<Account>();
for (Account a : Trigger.new) {
updates.add(new Account(Id = a.Id, Description = 'Set in after trigger'));
}
update updates;
}This works, but it costs a second DML on the same record. It also fires the update triggers on Account again. If you only need to change the record's own fields, use a before trigger. Reserve the after-trigger version for values that depend on the Id or on data that exists only after the save.
| Capability | Before trigger | After trigger |
|---|---|---|
| `Id` on insert | `null` | Populated |
| Edit `Trigger.new` fields | Yes, without DML | No, read-only |
| Create related records using this Id | Not possible on insert | Yes |
| Changing the same record | Free | Needs extra DML |
| Sees formula and system field values | Not on insert | Yes |
Touching related records
After triggers are the normal place to create or update other objects. Typical cases:
- Create child records such as tasks, contacts, or custom detail records.
- Update a parent record when a child changes.
- Insert audit or history records.
- Start asynchronous work, such as a Queueable job, that needs the saved Ids.
When you update related records, collect them first, deduplicate, and run one DML statement. The next example updates each parent Account once, even if several Contacts in the same save point to it.
trigger ContactAfterInsert on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
List<Account> accounts = new List<Account>();
for (Id accountId : accountIds) {
accounts.add(new Account(Id = accountId, Description = 'Has contacts'));
}
update accounts;
}Each DML statement on a related record can fire that object's own triggers, validation rules, and flows. They run inside the same transaction, so their governor limit usage adds to yours. Keep this in mind when a trigger cascades through several objects.
An after update trigger can run twice
Workflow field updates run after the after trigger. If a workflow rule changes a field, the platform fires the before update and after update triggers one more time for that record. Only that second pass sees the new values from the workflow update. Trigger.old and Trigger.new in the second pass differ from the first, and the platform does not re-run before-save flows or validation twice in the same way. Your trigger code must tolerate being called again for the same record.
A static variable lives for the whole transaction, so it can remember which records you have handled.
public class TriggerGuard {
public static Set<Id> processed = new Set<Id>();
}
trigger AccountAfterUpdate on Account (after update) {
List<Account> toProcess = new List<Account>();
for (Account a : Trigger.new) {
if (!TriggerGuard.processed.contains(a.Id)) {
TriggerGuard.processed.add(a.Id);
toProcess.add(a);
}
}
// Work only with toProcess here
}A guard that remembers Ids has a drawback. If the second pass carries a legitimate new change, the guard skips it. When that matters, compare Trigger.oldMap with Trigger.new and act only when the field you care about changed.
Errors in after triggers
You can reject a save from an after trigger with addError() on a record in Trigger.new. The method works there even though the fields are read-only. The error rolls back the whole transaction, including the record that was already saved to the database. An uncaught exception has the same effect. If you catch a DML failure with try/catch, the platform keeps the changes made before the failure, so catch errors only when you have a reason.
Choosing between before and after
- Does the logic change only the record being saved? Use a before trigger, or a before-save flow.
- Does it need the new record's Id or system-generated values? Use an after trigger.
- Does it create or update other records? Use an after trigger, or an after-save flow.
- Does it need to react to a change made by workflow? Plan for the second pass.
Exercise
A developer writes an after insert Account trigger that sets a.Industry = 'Retail' on each record in Trigger.new. It throws an error on save. Why, and how should they fix it?
Show answer
Records in Trigger.new are read-only in after triggers, so assigning a field throws a System.FinalException. Because the change affects only the record being saved and needs no Id, move the logic to a before insert trigger, where the assignment works without DML. If it must stay in an after trigger, create a new Account(Id = a.Id, Industry = 'Retail') and update it, which costs an extra DML and re-fires update triggers.
Exercise
An after update trigger sends a field change to a child record. A workflow rule on the same object also updates a field. How many times can the trigger run for one record, and what protects against double processing?
Show answer
It can run twice, because the workflow field update causes the update triggers to fire again. A static Set<Id> guard, or a comparison of Trigger.oldMap and Trigger.new values, stops the same record from being processed twice.