Sub topic 3
Choosing Before or After Triggers
This chapter assumes you know basic Apex syntax, sObjects, SOQL, and DML. It also assumes you know that triggers fire on insert, update, delete, and undelete. By the end you should be able to pick the right trigger context for a task and explain why the wrong one fails or wastes limits.
Where each context runs
Every save operation passes through a fixed sequence. A before trigger runs after the incoming values are loaded into memory and before the record is written to the database. An after trigger runs once the record has been written and has an ID, but the transaction has not committed yet. Both contexts run inside the same transaction and share the same governor limits.
The real order of execution has more steps than this. Flows, duplicate rules, and roll-up calculations also take part. The simplified version is enough for this chapter's decisions: before triggers see the record before it is saved, and after triggers see it after it is saved.
What you can do in each context
The difference in timing leads to different capabilities.
| Capability | Before trigger | After trigger |
|---|---|---|
| Change fields on the triggering record | Yes, by assigning to `Trigger.new` records | No, records in `Trigger.new` are read-only |
| Read the record ID on insert | No, the ID is `null` | Yes |
| Needs a DML statement to save changes to the triggering record | No | Yes, and it re-fires triggers |
| Create or update related records | Possible, but you cannot reference the new record's ID | Yes, with the ID available |
| Block the save with `addError` | Yes | Yes, and the transaction rolls back |
| Available on delete | Yes (`Trigger.old`) | Yes (`Trigger.old`) |
| Available on undelete | No | Yes |
Two rules explain most of this table.
- Use a before trigger when you only need to change or validate the triggering record's own fields.
- Use an after trigger when you need the record's ID or when the work affects other records.
Updating the triggering record: use before
Assigning to a field in a before trigger costs nothing extra. The platform saves the changed value as part of the original DML operation.
trigger AccountTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.Name != null) {
acc.Name = acc.Name.trim();
}
if (acc.AnnualRevenue != null && acc.AnnualRevenue > 1000000) {
acc.Rating = 'Hot';
}
}
}This trigger contains no SOQL and no DML. It loops over the whole list, so it is already bulk safe for any batch size up to 200. The earlier ContactTrigger examples in this tutorial follow the same pattern: they set c.Description on the records in Trigger.new and never call update.
If you try the same assignment in an after trigger, the platform rejects it at run time.
trigger AccountAfterTrigger on Account (after insert) {
for (Account acc : Trigger.new) {
// Throws: Record is read-only
acc.Rating = 'Hot';
}
}The error message is Record is read-only. The fix is usually to change the trigger to a before trigger. The alternative is to query a fresh copy of the record and update it, which costs a query and a DML statement and re-fires the account triggers. Avoid that unless the update depends on something only available after the save.
Working with related records: use after
Some work needs the ID of the saved record. The usual case is creating child records that point back to it. A before insert trigger cannot do this because Trigger.new records have no ID yet.
The OpportunityTrigger from the plan creates a Task with WhatId = opp.Id. That value is null in a before insert trigger, so the trigger must run after the save.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
OpportunityTriggerHandler.createFollowUpTasks(Trigger.new, Trigger.oldMap);
}
public with sharing class OpportunityTriggerHandler {
public static void createFollowUpTasks(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : newOpps) {
Boolean isWon = opp.StageName == 'Closed Won';
Boolean wasWon = oldMap != null
&& oldMap.get(opp.Id).StageName == 'Closed Won';
if (isWon && !wasWon) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}Notice the single insert tasks after the loop. The after context gives you IDs, and bulk DML keeps the trigger within the limit of 150 DML statements per transaction.
On update, the record already has an ID in both contexts. Related-record work in a before update trigger is therefore technically possible. Even so, an after trigger is the safer choice. If a later validation rule or another trigger fails, the whole transaction rolls back either way. The after trigger, however, runs once the record's final saved values are in place, so the changes it makes to related records are based on the values that actually saved. A before trigger can see values that a later step then changes.
Decision rules
Work through these questions in order.
- Does the work only change fields on the triggering record? Use before.
- Does the work validate the triggering record's own fields? Use before, so you reject bad data before the save.
- Does the work need the new record's ID, for example to create children? Use after.
- Does the work create, update, or delete other records? Use after.
- Does the work read values that other automation sets, or read formula or system-set fields such as
CreatedDateon insert? Use after. - Does the work run on undelete? Only after is available.
A single object often needs both. In that case, declare both contexts in one trigger and branch with context variables, or use a handler class with separate methods.
trigger OpportunityTrigger on Opportunity (
before insert, before update, after insert, after update
) {
if (Trigger.isBefore) {
OpportunityTriggerHandler.setDefaults(Trigger.new);
} else if (Trigger.isAfter) {
OpportunityTriggerHandler.createFollowUpTasks(Trigger.new, Trigger.oldMap);
}
}Keep one trigger per object. Several triggers on the same object and event run in no guaranteed order, which makes behavior hard to predict.
Validation and errors
Both contexts support addError. A before trigger is the usual place for validation, because it stops the record before the save and keeps the logic close to the fields it checks. addError on a field also attaches the message to that field in the UI.
trigger InvoiceLineTrigger on Invoice_Line__c (before insert, before update) {
for (Invoice_Line__c line : Trigger.new) {
if (line.Quantity__c != null && line.Quantity__c < 0) {
line.Quantity__c.addError('Quantity cannot be negative.');
}
}
}Calling addError in an after trigger also blocks the save, but the record has already been written inside the transaction. The platform rolls the write back. Validation placed in an after trigger therefore does extra work first and can leave side effects, such as completed DML on other records, to be rolled back with it.
Common mistakes
- Calling
updateonTrigger.newrecords in a before trigger. The change is unnecessary, and the DML re-fires the trigger. Assign the field instead. - Trying to change
Trigger.newfields in an after trigger. This throws the read-only error. Move the logic to a before trigger, or update a separate copy of the record. - Reading
opp.Idin before insert. The value isnull. Child records created with a null parent ID fail or attach to nothing. - Putting related-record DML in a before trigger. It can work on update but is fragile on insert. Use after.
- Updating the same object from its own after trigger. This re-fires the trigger and can recurse. A later chapter covers guarding against that.
Bulk safety applies to both
The choice of context does not change the batch size. Both contexts receive up to 200 records per invocation, and both share the transaction's limits of 100 SOQL queries and 150 DML statements for synchronous Apex. Every rule from the next chapters about keeping SOQL and DML out of loops applies equally to before and after triggers.
Exercise
A trigger on Opportunity must (1) set a custom field Region__c on each opportunity based on its Amount, and (2) create a Task for each new opportunity with WhatId set to the opportunity. Which context does each task need, and why?
Show answer
Setting Region__c belongs in a before insert and before update trigger, because assigning to Trigger.new fields is saved with the original DML and uses no extra statement. Creating the Task needs the opportunity's ID for WhatId, which is null in a before insert trigger, so it belongs in an after insert trigger. Collect the tasks in a list and insert them with one DML statement after the loop.
Exercise
This trigger throws Record is read-only when it runs. What is wrong, and what is the simplest fix?
trigger LeadTrigger on Lead (after insert) {
for (Lead l : Trigger.new) {
l.Status = 'Working';
}
}
Show answer
Records in Trigger.new cannot be modified in an after trigger. Because the change only affects the triggering record, the simplest fix is to change the event to before insert. The assignment then saves with the original operation and needs no DML statement.