Sub topic 2
Reading Trigger.new, Trigger.old, and the Context Flags
This chapter assumes you know basic Apex syntax, sObjects, and simple SOQL and DML. It also assumes you know that triggers fire on insert, update, delete, and undelete. Here you will learn which Trigger variables hold data, which ones are null in each event, and how to branch on the context flags without breaking bulk behavior.
What the Trigger class gives you
Inside a trigger, the system provides a static class named Trigger. Its members describe the event that fired and the records involved. They are read-only context. Your code reads them but never assigns to them.
The members fall into two groups.
- Record collections:
Trigger.new,Trigger.old,Trigger.newMap, andTrigger.oldMap. - Context flags and counters:
Trigger.isInsert,Trigger.isUpdate,Trigger.isDelete,Trigger.isUndelete,Trigger.isBefore,Trigger.isAfter,Trigger.isExecuting,Trigger.operationType, andTrigger.size.
Every record collection holds up to 200 records per invocation, so always treat them as lists, never as a single record.
The record collections
| Variable | Type | Holds | Available in |
|---|---|---|---|
| `Trigger.new` | `List<SObject>` | New versions of the records | insert, update, undelete |
| `Trigger.old` | `List<SObject>` | Old versions of the records | update, delete |
| `Trigger.newMap` | `Map<Id, SObject>` | New versions keyed by ID | before update, after insert, after update, after undelete |
| `Trigger.oldMap` | `Map<Id, SObject>` | Old versions keyed by ID | update, delete |
Two details cause most of the errors in practice.
First, the variables that do not apply to an event are null, not empty. On insert, Trigger.old and Trigger.oldMap are null. On delete, Trigger.new and Trigger.newMap are null. Looping over a null list throws a System.NullPointerException.
Second, records in a before insert trigger have no ID yet. That is why Trigger.newMap is not available in before insert. The IDs are assigned when the records are saved, so the map is first available in after insert.
Which records can you change?
In a before trigger, the objects in Trigger.new are editable. Setting a field on them changes what is saved, and you need no DML statement. In an after trigger, Trigger.new is read-only. Assigning a field there throws a runtime error. If you need to change the triggering records after save, you must query fresh copies and run DML on them. Chapter 3 covers that choice in more detail.
trigger AccountTrigger on Account (before insert, before update) {
for (Account acct : Trigger.new) {
// Allowed: this is a before trigger, so the change is saved
// with the record and needs no DML statement.
if (acct.Name != null) {
acct.Name = acct.Name.trim();
}
}
}The context flags
The Boolean flags tell you which event and which timing fired the trigger. A trigger that lists several events needs them to branch.
| Flag | True when |
|---|---|
| `Trigger.isInsert` | The trigger fired because of an insert |
| `Trigger.isUpdate` | The trigger fired because of an update |
| `Trigger.isDelete` | The trigger fired because of a delete |
| `Trigger.isUndelete` | The trigger fired because of an undelete |
| `Trigger.isBefore` | The trigger runs before records are saved |
| `Trigger.isAfter` | The trigger runs after records are saved |
| `Trigger.isExecuting` | The current code is running inside a trigger |
| `Trigger.size` | Not a flag. The total number of records in the invocation, old and new |
Exactly one of the event flags (isInsert, isUpdate, isDelete, isUndelete) is true per invocation. Exactly one of isBefore and isAfter is true as well. Combining one from each pair identifies the context, such as before insert or after update.
Trigger.operationType returns the same information as a System.TriggerOperation enum value, such as BEFORE_INSERT or AFTER_UPDATE. It works well in a switch statement and reads more clearly than nested if checks.
trigger ContactTrigger on Contact (
before insert, before update, after insert, after delete
) {
switch on Trigger.operationType {
when BEFORE_INSERT, BEFORE_UPDATE {
System.debug('Preparing ' + Trigger.new.size() + ' contacts');
}
when AFTER_INSERT {
System.debug('Saved ' + Trigger.new.size() + ' new contacts');
}
when AFTER_DELETE {
System.debug('Deleted ' + Trigger.old.size() + ' contacts');
}
when else {
System.debug('Unhandled: ' + Trigger.operationType);
}
}
}Which variables are safe where
The table below shows which collections are populated in each context. "null" means the variable has no value and any use of it will fail.
| Context | `new` | `old` | `newMap` | `oldMap` |
|---|---|---|---|---|
| before insert | list (no IDs) | null | null | null |
| after insert | list | null | map | null |
| before update | list | list | map | map |
| after update | list | list | map | map |
| before delete | null | list | null | map |
| after delete | null | list | null | map |
| after undelete | list | null | map | null |
Use this table to decide what your code may touch. If one trigger handles insert and update, any code that reads oldMap must first check that the map is not null, or check Trigger.isUpdate.
Reading old values safely
A common task is to compare a field's new value with its old value. This is only meaningful on update, so the code must guard the lookup.
trigger OpportunityStageTrigger on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
Boolean stageChanged = false;
if (Trigger.isInsert) {
// On insert there is no old value. Treat a set stage as a change.
stageChanged = opp.StageName != null;
} else if (Trigger.isUpdate) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
stageChanged = opp.StageName != oldOpp.StageName;
}
if (stageChanged) {
opp.Description = 'Stage is now ' + opp.StageName;
}
}
}Using Trigger.oldMap.get(opp.Id) is better than looping over Trigger.old in parallel by index. A map lookup stays correct even if you later filter the new records into a smaller list. Chapter 10 builds on this pattern for change detection.
The same loop, in bulk
Because the collections are lists, the trigger body is nearly always a loop. The context variables do not remove the need to avoid SOQL and DML inside that loop. The next diagram shows how the system hands the variables to your trigger for a large operation.
The three invocations belong to the same transaction in this example, so they share one set of governor limits. A query that runs once per invocation runs three times for this load. A query that runs once per record would run 450 times.
Common errors
The mistakes below account for most context-variable bugs.
- Looping over
Trigger.oldon insert. The list isnull, so the loop throws aNullPointerException. Guard withTrigger.isUpdateorTrigger.isDelete. - Reading
Trigger.newMapin before insert. The map isnullbecause no IDs exist. UseTrigger.newinstead. - Assuming
Trigger.new[0]is the whole story. The list can hold 200 records. Code that reads only the first record silently ignores the rest. - Editing
Trigger.newin an after trigger. Fields on those records are read-only, and the assignment throws an error. Move the change to a before trigger, or run DML on separately queried records. - Using
Trigger.sizeas the count of new records. On update it counts new and old versions together in some uses of the platform's internal batching, so useTrigger.new.size()when you need a record count. - Calling
Trigger.oldrecords modifiable. Old values are always read-only, in every context.
Using the flags in a helper method
Triggers often call helper methods that do not know their context. Passing the lists as arguments keeps those methods testable, because a test can build the lists without firing a trigger.
public with sharing class ContactHelper {
public static Integer countChangedEmails(
List<Contact> newContacts,
Map<Id, Contact> oldMap
) {
Integer changed = 0;
for (Contact c : newContacts) {
if (oldMap == null || !oldMap.containsKey(c.Id)) {
// Insert, or a record with no previous version.
if (c.Email != null) {
changed++;
}
} else if (c.Email != oldMap.get(c.Id).Email) {
changed++;
}
}
return changed;
}
}The oldMap == null check handles insert. The containsKey check handles any record that has no old version. The method never reads Trigger directly, so you can call it from a unit test with plain lists.
Exercises
Exercise
A trigger declared on (before insert, before update, before delete) contains the line for (Account a : Trigger.new) with no other checks. Which event causes a runtime error, and why?
Show answer
Before delete. Trigger.new is null on delete, so the loop throws a NullPointerException. The code should check Trigger.isDelete and use Trigger.old for that event.
Exercise
You need the previous Status__c of each record in a before update trigger. Which expression returns it for a record rec in Trigger.new, and why is that better than reading Trigger.old[i] by index?
Show answer
Trigger.oldMap.get(rec.Id).Status__c. The map is keyed by ID, so the lookup stays correct even if you skip or reorder records while looping. An index into Trigger.old only works if you keep the two lists aligned.
Exercise
In a before insert trigger, a developer writes Trigger.newMap.get(c.Id). What happens, and what should they use instead?
Show answer
Trigger.newMap is null in before insert because records have no IDs yet, so the call throws a NullPointerException. They should loop over Trigger.new directly.