Sub topic 5
Before triggers: changing values without DML
This chapter assumes you can write a basic Apex trigger, know what Trigger.new is, and understand insert and update DML. It covers one step of the save: the before trigger.
Where before triggers run
A before trigger runs after the record has been loaded and the new values applied. It also runs after system validation and any before-save flows. At that point the record is not yet in the database. Custom validation rules have not run either, so your changes are still checked afterward.
Change values without DML
In a before trigger, Trigger.new holds the records that are about to be saved. You can change their fields directly. Salesforce saves those changes with the record, so you don't call update.
trigger AccountOrderDemo on Account (before insert, before update, after insert, after update) {
if (Trigger.isBefore) {
System.debug('BEFORE ' + Trigger.operationType);
for (Account a : Trigger.new) {
if (a.Description == null) {
a.Description = 'Set in before trigger';
}
}
} else {
System.debug('AFTER ' + Trigger.operationType);
}
}The loop sets Description on each record that lacks one. There is no DML statement. The else branch runs in the after events, and it only writes a debug line, because Trigger.new is read-only there.
This is the main reason to prefer a before trigger for field changes on the same record. It costs no extra DML statement and does not start a second save.
The Id is not available on insert
On before insert, the record has not been written, so a.Id is null. If you need the Id, for example to create child records that point to the new record, use an after trigger. A before trigger is the right place for logic that only needs the record's own field values.
Common errors
- Calling
updateonTrigger.newin a before trigger. This is unnecessary. It can also cause errors or recursion, because Salesforce already saves your changes. - Reading
Idinbefore insert. The value isnull. Move that logic toafter insert. - Writing one record at a time. Triggers receive up to 200 records per batch. Loop over
Trigger.newand never assume a single record. - Expecting validation to see the old value. Custom validation rules run after your trigger. They check the values your trigger set.
- Running queries or DML inside the loop. The governor limits are shared across the whole transaction, so collect values first and query once.
Exercise
A before insert trigger on Contact tries to create a Task with WhatId = c.Id. Why does this fail to link the Task, and where should the code move?
Show answer
In before insert the Contact has not been saved, so c.Id is null and the Task has nothing to point to. Move the Task creation to an after insert trigger, where the Id exists, and insert all the Tasks in one bulk DML statement.