Sub topic 4
Prefer Before Triggers: Change Records Without DML
This chapter assumes you can write a basic Apex trigger, know the insert and update statements, and know the main governor limits. The previous chapters showed how a trigger ends up calling itself. This chapter covers the simplest fix: don't issue the extra DML at all.
The problem: an after trigger that updates its own records
The recursion example from earlier looks like this:
trigger AccountTrigger on Account (after update) {
List<Account> toUpdate = new List<Account>();
for (Account acc : Trigger.new) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
update toUpdate; // fires this trigger again, with no guard
}The update saves the Accounts a second time, so the after update event fires again. The trigger runs again and issues the same update. The loop continues until Salesforce stops it with a "maximum trigger depth exceeded" error.
Guards such as static variables can stop the loop, but they add state that you must reason about and test. If you can remove the DML instead, there is nothing to guard.
Why before triggers need no DML
A before trigger runs before Salesforce writes the records to the database. The records in Trigger.new are in memory and not yet saved. If you change a field on one of them, Salesforce saves the new value as part of the original operation.
trigger AccountTrigger on Account (before update) {
for (Account acc : Trigger.new) {
acc.Description = 'Reviewed';
}
}This trigger has no update statement, so nothing re-fires it. The record is saved once, with the new Description.
An after trigger runs once the records have been written to the database (they are not yet committed). At that point Trigger.new is read-only. Assigning a field fails at run time:
trigger AccountTrigger on Account (after update) {
for (Account acc : Trigger.new) {
acc.Description = 'Reviewed'; // System.FinalException: Record is read-only
}
}To change a saved record from an after trigger, you must run DML, and that DML can re-fire the trigger. Choosing the before event avoids the problem.
Before and after compared
| Question | Before trigger | After trigger |
|---|---|---|
| Are the records saved yet? | No | Yes, within the open transaction |
| Can you edit fields on `Trigger.new` records? | Yes | No, they are read-only |
| Do you need DML to change the triggering records? | No | Yes |
| Does that DML re-fire the trigger? | Not applicable | Yes |
| Is the record `Id` available on insert? | No | Yes |
| Are system-set and formula values final? | No | Mostly yes |
Deciding which event to use
The rule of thumb: use a before trigger to change the record that is being saved. Use an after trigger to react to a saved record, for example to create or update other records.
Setting values on insert and update
Most before-trigger logic falls into three groups: default values, derived values, and normalization. A single handler method can cover both before insert and before update:
public class AccountTriggerHandler {
public static void beforeSave(List<Account> newList) {
for (Account acc : newList) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Reviewed';
}
if (acc.Name != null) {
acc.Name = acc.Name.trim();
}
}
}
}trigger AccountTrigger on Account (before insert, before update) {
AccountTriggerHandler.beforeSave(Trigger.new);
}Because the handler only edits Trigger.new, running the trigger twice would give the same result. This is the property you want: logic that is idempotent, meaning that applying it again changes nothing.
What a before trigger cannot do
Moving logic to a before trigger is not always possible. Know these limits before you rewrite working code.
- No record Id on insert. In
before insert,acc.Idisnull. You cannot create child records that point to the new parent. Useafter insertfor that. - No changes to other records without DML. Editing
Trigger.newonly affects the triggering records. Updating Contacts when an Account changes still needs anupdatestatement, and that requires an after trigger or a before trigger with explicit DML on a different object. - Not available on delete.
Trigger.newisnullin delete triggers, and there is nothing to edit. UseTrigger.oldfor read-only checks, for example to calladdError()on a record and block the delete. - The
Idfield cannot be changed. Assigning toIdon an existing record in a before update trigger fails. - Formula fields and some system fields are not final. Formula values are calculated after the before triggers run, so reading one in a before trigger can give you a stale or empty value. Fields such as
CreatedDateare not set yet on insert. - Later steps can overwrite your values. Validation rules run after before triggers. If a workflow field update changes the record afterward, the update triggers fire once more. Your before trigger must tolerate that extra run, which is another reason to keep it idempotent.
Do not try to call update on the records in Trigger.new from inside a before trigger. It is unsupported and unnecessary, because the platform already saves your edits.
When an after trigger is the right tool
Sometimes DML is the whole point. This trigger copies a changed rating to related Contacts:
trigger AccountContactSync on Account (after update) {
Map<Id, Account> changed = new Map<Id, Account>();
for (Account acc : Trigger.new) {
if (acc.Rating != Trigger.oldMap.get(acc.Id).Rating) {
changed.put(acc.Id, acc);
}
}
if (changed.isEmpty()) {
return;
}
List<Contact> contacts = [
SELECT Id, AccountId
FROM Contact
WHERE AccountId IN :changed.keySet()
];
for (Contact c : contacts) {
c.Description = changed.get(c.AccountId).Rating;
}
update contacts;
}This trigger does not re-fire itself. It updates Contacts, not Accounts, so no after update event on Account follows. It also compares the new and old Rating, so the logic only runs for records that changed. The next chapter covers that check in detail.
The risk that remains is indirect recursion. If a Contact trigger or a flow updates the parent Account, the Account trigger runs again through the other object. Use the guards from the following chapters in that case. A before trigger does not remove that risk, because the DML here targets a different object.
A common mixed pattern
A single object often needs both kinds of work. Split the work by context in the handler and route from one trigger:
trigger AccountTrigger on Account (before insert, before update, after update) {
if (Trigger.isBefore) {
AccountTriggerHandler.beforeSave(Trigger.new);
} else if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}Keep the field edits for the triggering records in beforeSave. Keep the DML on other records in afterUpdate. With this split, the only after-trigger DML left is the kind that really needs it, so you need far fewer recursion guards.
Governor limits benefit too
Removing a self-update also saves resources. Each re-fired trigger repeats its SOQL queries and DML statements inside the same transaction. These count against the same limits, such as 100 SOQL queries and 150 DML statements for synchronous Apex. Editing Trigger.new in a before trigger uses no DML statements and no extra rows.
Checklist for a new trigger
- Ask whether the logic only changes the record that fired the trigger. If yes, use a before event.
- If you need the new record
Idor a calculated value, use an after event and keep the DML on other records or objects. - Compare new and old values so the logic runs only when a relevant field changed.
- If DML on the same object is unavoidable, add a guard, as the next chapters show.
Exercise
A developer writes trigger LeadTrigger on Lead (after insert) { for (Lead l : Trigger.new) { l.Status = 'Working'; } }. It fails with "Record is read-only". The goal is to set the Status on each Lead being inserted. What is the smallest correct fix, and why does it avoid recursion?
Show answer
Change the event to before insert. In a before trigger the records in Trigger.new are not saved yet, so assigning l.Status = 'Working' is allowed and Salesforce saves the value as part of the original insert. The fix adds no update statement, so nothing re-fires the trigger. It would need an after trigger plus DML only if the logic needed the new Lead Id or had to change other records.
Exercise
Name two situations where a before trigger cannot replace an after trigger that uses DML.
Show answer
First, when the logic must create or update records related to the saved record that need its Id, because the Id is null in before insert. Second, when it must change records other than those in Trigger.new, such as updating child Contacts when an Account changes, because editing Trigger.new only affects the triggering records. (Delete triggers are another case: Trigger.new is null there.)