Sub topic 7
Branching with isInsert, isBefore and friends
This chapter assumes you can write a basic trigger, read Trigger.new and Trigger.old, and know which events each variable is populated in. The previous chapters covered those. Here you will use the Boolean context variables to run the right code for the right event. You will also see where Trigger.isExecuting and Trigger.size fit in.
Why a trigger needs flags
A trigger can listen to several events at once. This declaration fires for five of them:
trigger AccountTrigger on Account (before insert, before update, before delete, after insert, after update) {
// one body, five possible contexts
}The body runs on every one of those events, but each event allows different things. On a delete, Trigger.new is null. In a before insert, records have no Id yet. In an after trigger, records are read-only. Code that ignores this fails at run time with a null reference or a "record is read-only" error.
The Boolean flags on the Trigger class tell you which event is running, so you can guard each block of logic.
The flags
| Variable | True when |
|---|---|
| `Trigger.isBefore` | The trigger is running before records are saved |
| `Trigger.isAfter` | The trigger is running after records are saved |
| `Trigger.isInsert` | The DML operation is an insert |
| `Trigger.isUpdate` | The DML operation is an update (this includes the update half of an upsert) |
| `Trigger.isDelete` | The DML operation is a delete |
| `Trigger.isUndelete` | Records are being recovered from the Recycle Bin |
| `Trigger.isExecuting` | The current code was started by a trigger |
| `Trigger.size` | The number of records in this invocation |
The first six form two groups, and exactly one flag in each group is true. One of isBefore and isAfter is true. One of isInsert, isUpdate, isDelete and isUndelete is true. Together they identify one of the seven events:
- before insert, before update, before delete
- after insert, after update, after delete, after undelete
There is no before undelete. If you check Trigger.isBefore && Trigger.isUndelete, the result is always false.
Combining flags
Nest the checks, or combine them with && and ||. Here is a trigger that validates and defaults data in the before phase and creates related records in the after phase:
trigger AccountTrigger on Account (before insert, before update, before delete, after insert) {
if (Trigger.isBefore) {
if (Trigger.isInsert || Trigger.isUpdate) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountTrigger';
}
}
}
if (Trigger.isDelete) {
for (Account a : Trigger.old) {
if (a.AnnualRevenue != null && a.AnnualRevenue > 1000000) {
a.addError('High-revenue accounts cannot be deleted.');
}
}
}
}
if (Trigger.isAfter && Trigger.isInsert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(
Subject = 'Follow up with new account',
WhatId = a.Id
));
}
insert tasks;
}
}Each block reads only the collection that exists in its event. The delete block uses Trigger.old, because Trigger.new is null there. The after insert block uses a.Id, which is only set after the save. The insert tasks statement runs once, outside the loop.
Grouping conditions
Trigger.isInsert || Trigger.isUpdate is the most common grouping. It covers the two events where Trigger.new is populated and, in a before trigger, editable. When you need Trigger.oldMap for comparisons, narrow the check to Trigger.isUpdate. On insert there is no old version, and Trigger.oldMap is null.
trigger OpportunityTrigger on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
if (opp.StageName == 'Closed Won' && opp.CloseDate == null) {
opp.CloseDate = Date.today();
}
if (Trigger.isUpdate) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName != oldOpp.StageName) {
opp.Description = 'Stage changed from ' + oldOpp.StageName;
}
}
}
}The first check is safe for both events. The oldMap lookup sits inside if (Trigger.isUpdate). Without that guard, the trigger would throw a System.NullPointerException on every insert.
When a flag is redundant
If a trigger is declared for one event only, its flags are constant. In trigger T on Account (before insert), Trigger.isBefore and Trigger.isInsert are always true. Checking them adds noise.
Flags matter when:
- One trigger lists several events, as in the examples above.
- You pass work to a handler class that serves several events.
- You want the code to stay correct if someone adds an event to the declaration later.
A common team convention is one trigger per object. That makes the flags the standard way to organize logic. Moving the logic into a handler class is covered in a later chapter.
Trigger.isExecuting
Trigger.isExecuting is true when the code that is running was started by a trigger. It is most useful in a class that triggers and other callers share. Other callers include test methods, Visualforce controllers, and anonymous Apex.
public class AuditHelper {
public static void log(String message) {
if (Trigger.isExecuting) {
System.debug('From trigger (' + Trigger.operationType + '): ' + message);
} else {
System.debug('Not from a trigger: ' + message);
}
}
}Outside a trigger, isExecuting is false and Trigger.new is null. Reading other trigger variables from shared code is fragile, so check isExecuting first. A cleaner design passes the records or the context into the method as parameters.
The method uses Trigger.operationType, which returns a System.TriggerOperation value. It is an alternative to the Boolean flags and has its own chapter.
Trigger.size
Trigger.size is the number of records in the current invocation. It counts records in Trigger.new for insert, update and undelete, and in Trigger.old for delete.
Salesforce passes records to a trigger in chunks of up to 200. If a single DML statement or API call affects 450 records, the trigger runs three times in the same transaction, with sizes 200, 200 and 50. Trigger.size reports the size of the current chunk, not the full operation.
You can use it to skip work on empty input or to log batch sizes:
trigger ContactTrigger on Contact (after insert, after update) {
if (Trigger.size == 0) {
return;
}
System.debug('Processing ' + Trigger.size + ' contacts in this chunk');
}Common mistakes
- Forgetting the update guard. Using
oldMapin a trigger that also handles insert causes a null reference on insert. - Using
Trigger.newin delete branches. UseTrigger.oldinstead. - Branching on
isAfterand then editingTrigger.new. Field changes to records in after triggers raise an error. Do those edits in a before trigger. - Checking
Trigger.isBefore && Trigger.isUndelete. That event does not exist, so the block never runs. - Assuming
Trigger.sizeis the total operation size. It is the size of one chunk of at most 200.
Exercise
Exercise
A trigger on Case is declared for before insert, before update, after update. You want to set Priority = 'High' on every Case whose Origin is 'Phone', but only before the record is saved. Write the condition that guards this logic, and say which collection you iterate.
Show answer
Use if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) and iterate over Trigger.new. Setting fields on the records in Trigger.new is allowed in before triggers, and the changes are saved without a DML statement. Because the trigger has no before delete event, if (Trigger.isBefore) alone would also work, but the longer form stays correct if someone adds before delete later. Do not make this change in the after update branch, because records in Trigger.new are read-only there.
Exercise
A single insert statement inserts 450 Account records, and an after insert trigger logs Trigger.size. What values does it log?
Show answer
It logs 200, 200 and 50. Salesforce runs the trigger once per chunk of up to 200 records, and Trigger.size reports the size of the current chunk.