Sub topic 5
Before triggers: changing values without DML
This chapter assumes you can write a basic Apex trigger, know what Trigger.new and Trigger.old are, and understand insert, update, and delete DML. It covers what a before trigger can do, why it needs no DML, and where it sits in the order of execution.
Where before triggers run
Before triggers run early in the save. By this point Salesforce has loaded the record, applied the incoming values, run system validation, and run any before-save record-triggered flows. The record has not been written to the database yet.
Two consequences follow from this position:
- A before trigger sees the values that before-save flows have already set.
- Anything the trigger changes is checked by the custom validation rules that run next. The trigger can fix a value so a rule passes. It can also break one.
Why no DML is needed
In a before trigger, Trigger.new holds the same in-memory records that Salesforce is about to save. Assigning a field on one of those records changes what gets written. The platform performs the single insert or update afterward.
trigger AccountBeforeSave on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (a.Name != null) {
a.Name = a.Name.trim();
}
if (String.isBlank(a.Description)) {
a.Description = 'Set in before trigger';
}
if (Trigger.isUpdate) {
Account previous = Trigger.oldMap.get(a.Id);
if (a.Rating == 'Hot' && previous.Rating != 'Hot') {
a.Description = 'Became Hot on ' + Date.today().format();
}
}
}
}This trigger makes no insert or update call, and it saves no queries or DML statements against the limits. It changes the record in place. The Trigger.isUpdate check guards Trigger.oldMap, which is null on insert.
Calling update Trigger.new inside a before trigger raises an error, because DML on the records already being saved is not allowed. Plain field assignment is the correct approach.
What is available in each before event
| Event | `Trigger.new` | `Trigger.old` / `oldMap` | `Trigger.newMap` | Record Id |
|---|---|---|---|---|
| before insert | Writable | Not available | Not available | `null` |
| before update | Writable | Available | Available | Present |
| before delete | Not available | Available | Not available | Present |
The Id is null in before insert because the record has not been written yet. This is why before insert has no newMap: the map is keyed by Id. If your logic needs the new record's Id, for example to set WhatId on a child, move that part to an after insert trigger.
Undelete has no before event. Only an after undelete trigger exists.
Common uses
Before triggers fit work that depends only on the record being saved:
- Defaulting or normalizing field values, such as trimming text or setting a status.
- Copying a value from another field on the same record.
- Computing a field from
Trigger.oldMapcomparisons, such as stamping a date when a field changes. - Blocking a save with
addError.
trigger OpportunityBeforeSave on Opportunity (before insert, before update) {
for (Opportunity o : Trigger.new) {
if (o.StageName == 'Closed Won' && o.Amount == null) {
o.Amount.addError('Amount is required when the stage is Closed Won.');
}
}
}Calling addError on a field marks that record as failed. In an all-or-none DML operation, one failed record makes the whole transaction roll back. With partial-success DML such as Database.insert(records, false), the other records can still save.
Edge cases and gotchas
- Formula fields are not recalculated yet. A formula field read in a before trigger shows its previous value. On insert it is
null. Formulas are recalculated after the save. - Record Id cannot be changed. Assigning to
Idon a record inTrigger.newis an error. - Related records need DML. Field assignment works only for the records in
Trigger.new. Changing a parent, child, or unrelated record still requires DML, which belongs in an after trigger. - Your changes may not stick. Later steps can still change the record. Validation rules can reject it, and workflow field updates can overwrite values after the save.
- Updates can fire the trigger again. A workflow field update causes before and after update triggers to run a second time. Make your before trigger idempotent, meaning that running it twice gives the same result.
Before trigger or before-save flow
Both change field values without DML, and the flow runs first. A before-save flow is usually the right choice when the logic is simple field setting that an admin should be able to maintain. Use a before trigger when you need Apex features such as complex collections, helper classes, or detailed error handling. If you use both on the same object, the trigger sees the flow's output. Later chapters cover ordering.
Exercise
A before insert trigger on Account needs to create a Task whose WhatId points to the new Account. Why does this fail in a before insert trigger, and where should the code go?
Show answer
In before insert the Account has not been saved, so a.Id is null and the Task cannot reference it. Also, creating a Task needs DML, which a before trigger should not use to change the saving record's related data. Put the code in an after insert trigger, where the Id exists, and insert all Tasks in one bulk DML statement.
Exercise
A before update trigger contains update Trigger.new; to save its field changes. What happens, and what should replace it?
Show answer
The statement raises an error, because DML on Trigger.new is not allowed in a trigger. Remove it and assign the fields directly on each record in Trigger.new. Salesforce saves those changes when the update completes.