Sub topic 6
Which variables exist in which event
This chapter assumes you can write a basic Apex trigger and know the seven trigger events. It also assumes you know the four record collections: Trigger.new, Trigger.old, Trigger.newMap and Trigger.oldMap. The question here is which of them hold data in each event. Reading a variable that is null is one of the most common trigger bugs. It usually appears only when a second event is added to a trigger that already works.
Why availability depends on the event
Each variable describes a version of the record, and the event decides which versions exist.
- A new version exists when the operation writes a record: insert, update, or undelete.
- An old version exists when the record was already in the database before the operation: update or delete.
- A map keyed by Id needs Ids. Records in a before insert trigger have not been saved yet, so they have no Id.
Each rule follows from that reasoning. An insert has no old version, so Trigger.old is null. A delete has no new version, so Trigger.new is null. A before insert record has no Id, so Trigger.newMap is null.
The availability table
| Event | `Trigger.new` | `Trigger.newMap` | `Trigger.old` | `Trigger.oldMap` |
|---|---|---|---|---|
| before insert | Yes, editable | `null` | `null` | `null` |
| after insert | Yes, read-only | Yes | `null` | `null` |
| before update | Yes, editable | Yes | Yes | Yes |
| after update | Yes, read-only | Yes | Yes | Yes |
| before delete | `null` | `null` | Yes | Yes |
| after delete | `null` | `null` | Yes | Yes |
| after undelete | Yes, read-only | Yes | `null` | `null` |
Three patterns in the table are worth memorizing:
- Update is the only event with all four variables. It is also the only event where you can compare old and new values.
- Delete uses only the old side. Read
Trigger.oldorTrigger.oldMap. TheaddErrorexample in the previous chapters calledaddErroron records fromTrigger.oldfor this reason. - Before insert is the odd one. It has
Trigger.newbut no map, because the records have no Ids yet.
Undelete has only an after event. Records come back from the Recycle Bin with their original Ids, so Trigger.newMap is populated. There is no previous version to compare against, so Trigger.old is null.
Editable versus read-only
Availability is not the same as writability. Trigger.new is editable only in before insert and before update. In every after event the records are read-only, and assigning to a field throws a System.FinalException. Records in Trigger.old and Trigger.oldMap are always read-only.
Seeing availability at runtime
A trigger that handles all seven events can pick the correct collection explicitly. The example below logs what is available in each case.
trigger AccountContextTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
List<Account> current;
if (Trigger.isDelete) {
current = (List<Account>) Trigger.old;
} else {
current = (List<Account>) Trigger.new;
}
System.debug('Operation: ' + Trigger.operationType);
System.debug('Records: ' + current.size());
System.debug('new is null: ' + (Trigger.new == null));
System.debug('old is null: ' + (Trigger.old == null));
System.debug('newMap is null: ' + (Trigger.newMap == null));
System.debug('oldMap is null: ' + (Trigger.oldMap == null));
}Run an insert, an update, and a delete in Developer Console anonymous Apex, then open the debug log. Compare the four is null lines with the table above. For a before insert you should see newMap is null: true, and for a delete you should see new is null: true.
Choosing a collection by decision
The diagram shows how to pick a safe starting point for the record loop.
Guarding access in a multi-event trigger
The most common failure is a trigger that works for update and then gets before insert added to its event list. The code below reads Trigger.oldMap without a guard, so it throws on insert:
trigger OpportunityStageTrigger on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
// NullPointerException on insert: Trigger.oldMap is null
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName != oldOpp.StageName) {
opp.Description = 'Stage changed';
}
}
}The fix is to branch before touching the old side. Insert counts as "changed" because there was no previous value.
trigger OpportunityStageTrigger on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
Boolean stageChanged = false;
if (Trigger.isInsert) {
stageChanged = opp.StageName != null;
} else {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
stageChanged = opp.StageName != oldOpp.StageName;
}
if (stageChanged) {
opp.Description = 'Stage set or changed';
}
}
}Trigger.isInsert and Trigger.isUpdate are safe to test in any event, because they are Booleans and are never null. Testing them first protects every collection access that follows.
Edge cases
- Empty versus null. A variable that is "not available" is
null. It is not an empty list.Trigger.old.size()on an insert throws aNullPointerException, and a check likeTrigger.old.isEmpty()fails the same way. Test withTrigger.isInsertorTrigger.old != nullfirst. - A map in a before insert. Code that builds its own map from
Trigger.newand expects Ids will findnullkeys. If you need to match records to related data in a before insert, use a field value such as an external Id or a lookup field. Do not use the record's own Id. - After insert gives you Ids, but not related data.
Trigger.newMap.keySet()works in an after insert, so you can use it in SOQLWHERE Id IN :ids. Formula fields and fields set by other automation may not be visible on the in-memory record. Query them if you need them. - Merges. When records are merged, the losing records fire delete triggers, so
Trigger.oldholds them. The surviving record fires an update trigger. - Bulk size is not a hint of the event.
Trigger.sizecounts records in the current chunk of up to 200. It is the same forTrigger.newandTrigger.old. It does not tell you whether a collection exists.
Quick reference for the Boolean flags
These flags help you branch before reading a collection. All are Boolean values, set for the current event.
| Flag | True when |
|---|---|
| `Trigger.isInsert` | The event is insert (before or after) |
| `Trigger.isUpdate` | The event is update (before or after) |
| `Trigger.isDelete` | The event is delete (before or after) |
| `Trigger.isUndelete` | The event is after undelete |
| `Trigger.isBefore` | The event is any before event |
| `Trigger.isAfter` | The event is any after event |
Combining them reproduces the table. For example, Trigger.isAfter && Trigger.isInsert means Trigger.newMap is populated and read-only, and Trigger.old is null.
Exercise
A trigger on Contact is declared for before insert, before update, before delete. It runs for (Contact c : Trigger.new) and fails on some saves with a NullPointerException. Which event causes the failure, and what is the smallest change that fixes it?
Show answer
The before delete event causes it, because Trigger.new is null in delete events. The smallest fix is to branch on Trigger.isDelete and loop over Trigger.old in that case, for example List<Contact> records = Trigger.isDelete ? (List<Contact>) Trigger.old : (List<Contact>) Trigger.new;. Alternatively, return early from the delete case before the loop.
Exercise
In which events is Trigger.newMap null, and why is it null in before insert even though Trigger.new is populated?
Show answer
Trigger.newMap is null in before insert, before delete, and after delete. In before insert, the records have not been saved, so they have no Ids yet. A map keyed by record Id cannot be built until the Ids exist. After insert it is populated.
Exercise
You need to compare a field's old and new values for each record. In which events can you do this, and which context variable gives you the old version by record Id?
Show answer
You can compare old and new values only in update events, before update and after update. Trigger.oldMap.get(record.Id) returns the old version. Trigger.oldMap is null for insert and undelete events, so check Trigger.isUpdate before using it in a multi-event trigger.