Sub topic 3
Choosing before or after triggers
This chapter assumes you can write basic Apex, know how SOQL and DML work, and have seen Trigger.new and the context flags. You will learn how to decide which timing a piece of trigger logic belongs in.
What differs between the two timings
A trigger runs either before or after Salesforce saves a record to the database. The timing decides what you can change and what information you have.
| Question | Before trigger | After trigger |
|---|---|---|
| Can you edit fields on `Trigger.new`? | Yes. Changes are saved without DML. | No. The records are read-only. |
| Is `Id` available on insert? | No. It is `null`. | Yes. |
| Can you create or update related records? | Possible, but you lack the new record's Id. | Yes. This is the usual place. |
| Can you block the save with `addError`? | Yes. | Yes, and the whole transaction rolls back. |
A rule for choosing
Ask what the logic needs to do.
- Use a before trigger to set or correct fields on the records being saved, or to validate them. This costs no DML statements, so it saves a governor limit.
- Use an after trigger when you need the record's
Id, or when you write to other records that refer to it.
Both timings in one trigger
This trigger stamps a field before the save, then creates a related task after it. Both parts loop over the whole list and run no queries inside the loops.
trigger OpportunityTrigger on Opportunity (before insert, after insert) {
if (Trigger.isBefore && Trigger.isInsert) {
for (Opportunity opp : Trigger.new) {
if (opp.Description == null) {
opp.Description = 'Created by trigger';
}
}
}
if (Trigger.isAfter && Trigger.isInsert) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : Trigger.new) {
tasks.add(new Task(
Subject = 'Review new opportunity',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
insert tasks;
}
}The before branch needs no update statement. The after branch reads opp.Id, which exists only once the record is saved. It also runs a single insert for the whole batch.
Common errors
- Setting a field in an after trigger. Assigning
opp.Description = 'x'on aTrigger.newrecord throws a read-only error. Move the logic to a before trigger. - Reading
Idin a before insert. The value isnull, so a lookup keyed on it fails quietly. Move that logic to an after trigger. - Calling
updateon the triggering records from an after trigger. This works, but it costs a DML statement and fires the triggers again. If you only need to change fields, do it in the before trigger.
Exercise
A requirement says that when an Opportunity is inserted, you must set its NextStep field to "Call customer" if it is blank, and create a Task linked to the new Opportunity. Which timing do you use for each part, and why?
Show answer
Set NextStep in a before insert trigger, because you can edit Trigger.new fields there without DML. Create the Task in an after insert trigger, because the Task needs the Opportunity Id, which is null before the save. Insert all Tasks with one DML statement on a list.