Sub topic 8
Changing field values in before triggers
This chapter assumes you know basic Apex syntax, how SOQL and DML work, and what governor limits are. It covers how a before trigger changes the records that are being saved, and what to watch for when you do.
Why before triggers can edit records directly
A before trigger runs after Salesforce has the incoming values in memory but before it writes the record to the database. The records in Trigger.new are the same objects that will be saved. If you change a field on one of them, the new value is saved with the record.
This means you don't need a DML statement. You also save a DML statement and a trigger re-run, which would count against your limits.
trigger AccountTrigger on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountTrigger';
}
}
}The loop visits every record in the batch. Each blank Description gets a default value, and Salesforce saves it with the rest of the record.
Which events allow edits
You can change fields in before insert and before update triggers. Records in Trigger.new are writable in those two events.
- In
before delete, onlyTrigger.oldexists, and it is read-only. There is nothing to save. - In
aftertriggers, the records inTrigger.neware read-only. Assigning to a field throws aSystem.FinalException. Trigger.oldis always read-only.
Don't call update on Trigger.new inside a before trigger. The record is not yet saved, and the call causes an error or a recursive re-run.
Changing a field only when something changed
Often you want to act only when a specific field moves to a specific value. In a before update trigger, compare the new record with the prior version in Trigger.oldMap.
trigger OpportunityTrigger on Opportunity (before update) {
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName != oldOpp.StageName && opp.StageName == 'Closed Won') {
opp.CloseDate = Date.today();
}
}
}Trigger.oldMap is keyed by record Id and holds the values from before the update. The trigger sets CloseDate only when StageName has just become Closed Won. Without the comparison, the date would be reset on every later edit to a closed opportunity.
Insert and update need different handling
Trigger.oldMap is null in insert events, so calling Trigger.oldMap.get(...) there throws a NullPointerException. New records also have no Id yet in a before insert trigger. If one trigger handles both events, check the context first.
trigger LeadDefaults on Lead (before insert, before update) {
for (Lead l : Trigger.new) {
if (Trigger.isInsert && l.LeadSource == null) {
l.LeadSource = 'Other';
}
if (Trigger.isUpdate && l.Status != Trigger.oldMap.get(l.Id).Status) {
l.Description = 'Status changed to ' + l.Status;
}
}
}Trigger.isInsert and Trigger.isUpdate guard each branch, so oldMap is read only during an update.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Calling `update Trigger.new` in a before trigger | Error or recursion | Assign to fields and let Salesforce save |
| Editing `Trigger.new` in an after trigger | `System.FinalException` | Move the logic to a before trigger, or query and update separate copies |
| Reading `Trigger.oldMap` on insert | `NullPointerException` | Guard with `Trigger.isUpdate` |
| Setting a value without checking for a change | Value overwritten on every save | Compare against `Trigger.oldMap` |
Exercise
Exercise
A before update trigger on Case should set Priority to 'High' only when Status changes to 'Escalated'. What two things from the trigger context do you need, and why is a DML statement not needed?
Show answer
You need Trigger.new for the updated Case records and Trigger.oldMap to read each Case's previous Status. Compare c.Status != Trigger.oldMap.get(c.Id).Status && c.Status == 'Escalated', then assign c.Priority = 'High'. No DML is needed because records in Trigger.new in a before trigger are saved with the change automatically.
Exercise
Why does this before insert code fail, and how do you fix it? Account old = Trigger.oldMap.get(a.Id);
Show answer
Trigger.oldMap is null in insert events, and new records have no Id yet, so the call throws a NullPointerException. Wrap the code in if (Trigger.isUpdate), or only use Trigger.oldMap in an update trigger.