Sub topic 3
Before versus after: when each runs and why it matters
This chapter covers the difference between before and after triggers. It assumes you can read basic Apex (loops, collections, Map), know what a record Id is, and understand that DML statements and SOQL queries count against governor limits. Trigger syntax and the seven events are covered in earlier chapters. Here the focus is on timing and what that timing allows.
Where the two timings sit in a save
When a record is saved, Salesforce runs before triggers first, then writes the record to the database (inside the open transaction), and then runs after triggers. The transaction is not committed until all processing finishes, so an error in an after trigger still rolls back everything.
Two consequences follow from this order:
- In a
beforetrigger, the record has not been written yet. On insert it has no Id. - In an
aftertrigger, the record has been written to the database inside the transaction. It has an Id, and any system-calculated values are populated.
What before triggers are for
Use a before trigger when you need to change the records that are being saved. Changes you make to the fields of Trigger.new are saved with the record. You do not issue a DML statement for them.
trigger AccountTrigger on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountTrigger';
}
}
}This is efficient. The record is already on its way to the database, so your edit costs no extra DML statement and does not cause another round of trigger execution for the same record.
A before trigger is the right choice for:
- Setting default values or normalizing data, such as trimming text or standardizing a phone format.
- Calculating a field from other fields on the same record.
- Validating data and rejecting the save with
addError, before any work has been done.
What after triggers are for
Use an after trigger when you need the saved state of the record. This usually means one of two things: you need the record Id, or you need to change other records.
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 WhatId field needs the new Account's Id. That Id does not exist during before insert, so this logic belongs in after insert. Notice that the tasks are collected in a list and inserted with one DML statement outside the loop.
An after trigger is the right choice for:
- Creating or updating related records, such as child records or records on another object.
- Anything that needs the Id of a record that was just inserted.
- Work that should happen only once the record is known to be saved, such as queuing asynchronous jobs.
Records in after triggers are read-only
In an after trigger, the records in Trigger.new cannot be modified. Assigning to a field on one of them throws a runtime error: "Record is read-only". The record has already been written, so a direct field assignment has nothing left to affect.
trigger AccountReadOnlyDemo on Account (after update) {
for (Account a : Trigger.new) {
// Throws System.FinalException: Record is read-only
a.Description = 'This fails in an after trigger';
}
}If you need to change the same record from an after trigger, you must query or construct a separate copy and update it with DML. That update is a second save of the record, so it fires the triggers again. This is costly and invites recursion, which a later chapter covers. Whenever the change is to the record being saved, move it to a before trigger.
Comparing the two
| Question | Before trigger | After trigger |
|---|---|---|
| Record written to the database? | No | Yes, inside the open transaction |
| Record Id on insert | Not yet available | Available |
| Can edit `Trigger.new` fields directly? | Yes | No, read-only |
| DML needed to save edits to the record? | No | Yes, on a separate copy of the record |
| Typical use | Defaults, calculations, validation | Related records, Id-dependent work |
| Rolled back if a later error occurs? | Yes | Yes |
Choosing between them: a decision rule
Ask what the requirement changes.
- If it changes the record being saved, use
before. - If it changes a different record, use
after. - If it needs the Id of a new record, use
after. - If it only needs to reject the save, prefer
before, so no other work is done first.
A single requirement can need both. For example, "set CloseDate when an Opportunity closes, and create a follow-up Task" is a before update change plus an after update insert. Put each part in the event where it belongs.
Validation and addError at each timing
addError blocks the save and attaches a message to the record or to a field. It works in both timings, and an error in either one rolls back the whole transaction. The difference is cost. An error raised in before stops processing early. An error raised in after happens once the database write is done, and any work already performed in the transaction is undone.
trigger AccountDeleteGuard on Account (before delete) {
for (Account a : Trigger.old) {
if (a.AnnualRevenue != null && a.AnnualRevenue > 1000000) {
a.addError('High-revenue accounts cannot be deleted.');
}
}
}Validation that depends only on the record's own values belongs in before. Validation that depends on related data created in the same transaction may need after. A later chapter on addError covers the details.
Common errors
- Editing
Trigger.newin anaftertrigger. This fails with "Record is read-only". Move the change tobefore, or update a separate copy of the record. - Reading
a.Idinbefore insert. The value isnullbecause the record has not been written. Useafter insert, or key your logic on another field. - Calling DML on
Trigger.newin abeforetrigger to save a field change. This is unnecessary. In abefore insertit can fail because the records have no Id. In abefore updateit can cause a recursive update. Assign fields and let the save proceed. - Re-updating the same record from
after update. This re-fires the trigger and can loop until the platform's depth limit stops it. Use abeforetrigger for the change. If a re-update is unavoidable, use a static guard. - Assuming
aftermeans committed. It does not. The data is visible to your code and to queries in the same transaction, but other users cannot see it until commit. If something later in the transaction fails, yourafterwork is rolled back too.
Why the same field edit costs different amounts
The choice is about more than correctness. Compare two ways of defaulting a field on update:
- In
before update, you assigna.Description = '...'. No DML count is used, no extra save happens, and the triggers run once. - In
after update, you must query or copy the record, change it, and callupdate. That uses a DML statement, adds to the rows counted against the limit, and re-fires the triggers on the same records.
Across a batch of 200 records, the second approach also needs the extra work to be bulk-safe, which means building a list and updating once. The first approach needs none of this.
Putting both timings together
This example uses one trigger with both timings. It defaults a field before save and creates a related record after save. It branches on Trigger.isBefore and Trigger.isAfter.
trigger AccountLifecycle on Account (before insert, after insert) {
if (Trigger.isBefore) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set before insert';
}
}
} else if (Trigger.isAfter) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(
Subject = 'Welcome call',
WhatId = a.Id
));
}
insert tasks;
}
}The before branch edits the record with no DML. The after branch uses a.Id, which exists only at that point, and issues a single insert outside the loop. Later chapters show how to organize this with Trigger.operationType and a handler class.
Exercise
A requirement says: "When an Opportunity is updated and its Amount is below 1000, set its Description to 'Small deal'. Also, when a new Opportunity is inserted, create a Task linked to it." For each of the two parts, state which event timing you would use and why. Then explain what happens if you try the first part in an after update trigger by assigning opp.Description directly.
Show answer
The first part changes the record being saved, so use before update and assign opp.Description on the records in Trigger.new. No DML is needed. The second part needs the new Opportunity's Id for the Task's WhatId, and the Id does not exist until the record is written, so use after insert and insert the Tasks in a list with one DML statement outside the loop. If you assign opp.Description in after update, Salesforce throws a read-only error because records in Trigger.new cannot be modified after the save. To make that change in after update you would have to update a separate copy of the record with DML, which fires the triggers again.
Exercise
A developer writes a before insert trigger that creates a child Contact for each new Account using WhatId-style linking with a.Id. The Contact's AccountId is always null. What is the cause, and what is the fix?
Show answer
In before insert the Account has not been written, so a.Id is null. Move the Contact creation to an after insert trigger, where a.Id is populated, and insert all Contacts with one DML statement after the loop.