Sub topic 2
Reading Trigger.new, Trigger.oldMap and Trigger.operationType
This chapter assumes you can read basic Apex (classes, methods, List, Set, Map). It also assumes you know the DML operations (insert, update, delete, undelete) and have heard of governor limits. It does not assume you have written a trigger handler.
A trigger does not receive arguments. Salesforce fills in a set of read-only values called trigger context variables, and your code reads them. Every handler you write later in this tutorial depends on these values, so it pays to know exactly what each one holds and when it is empty.
What an Apex trigger is and when it fires
An Apex trigger is code that runs automatically when records of one object are saved to the database. You choose when it runs by listing events in the trigger header:
trigger AccountTrigger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
new AccountTriggerHandler().run();
}There are seven events: before and after for insert, update, and delete, plus after undelete. A before trigger runs before the records are written, so it can still change them. An after trigger runs once the records have been written, so record Ids exist and related records can be created.
Salesforce runs the trigger once per batch of up to 200 records, not once per record. A data load of 1,000 accounts runs the trigger five times. Every trigger context variable is therefore a collection.
The context variables you will use most
The trigger context variables live on the Trigger class. These are the ones a handler reads.
| Variable | Type | Holds |
|---|---|---|
| `Trigger.new` | `List<SObject>` | The new versions of the records |
| `Trigger.old` | `List<SObject>` | The previous versions of the records |
| `Trigger.newMap` | `Map<Id, SObject>` | The new versions, keyed by Id |
| `Trigger.oldMap` | `Map<Id, SObject>` | The previous versions, keyed by Id |
| `Trigger.operationType` | `System.TriggerOperation` | An enum value naming the current event |
| `Trigger.size` | `Integer` | The number of records in this batch |
| `Trigger.isExecuting` | `Boolean` | `true` only while a trigger (or code it called) is running |
There are also Boolean flags: Trigger.isBefore, Trigger.isAfter, Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, and Trigger.isUndelete. They answer one question each. Trigger.operationType answers all of them with one value, which is why this tutorial uses it for dispatch.
Which variables are populated for which event
Not every variable has a value in every event. Reading an empty one gives you null, and calling a method on it throws a System.NullPointerException.
| Event | `new` | `newMap` | `old` | `oldMap` |
|---|---|---|---|---|
| before insert | yes | no | no | no |
| after insert | yes | yes | no | no |
| before update | yes | yes | yes | yes |
| after update | yes | yes | yes | yes |
| before delete | no | no | yes | yes |
| after delete | no | no | yes | yes |
| after undelete | yes | yes | no | no |
Two rules cover most of the table:
- A record has no previous version when it is inserted or undeleted, so
oldandoldMapare empty in those events. - A record has no new version when it is deleted, so
newandnewMapare empty in delete events.
The exception is newMap in before insert. The records have no Id yet, so there is nothing to use as a key. Use Trigger.new there.
Read-only and writable
Whether you may change the records depends on the timing:
- In a before trigger, you can assign to fields on the records in
Trigger.new. Salesforce saves your changes without an extra DML statement. This is the cheapest place to set defaults. - In an after trigger,
Trigger.newis read-only. Assigning a field throws aSystem.FinalException. To change a record after the save, query or build a fresh copy of it and run DML on that. Trigger.oldandTrigger.oldMapare read-only in every event.
Reading Trigger.operationType
Trigger.operationType returns a value of the System.TriggerOperation enum. These values are:
BEFORE_INSERTBEFORE_UPDATEBEFORE_DELETEAFTER_INSERTAFTER_UPDATEAFTER_DELETEAFTER_UNDELETE
A switch on statement works directly with an enum, and the compiler checks that each when label is a real value. A misspelled label fails at deploy time instead of silently never matching.
public with sharing class OperationLogger {
public static String describe(System.TriggerOperation op) {
switch on op {
when BEFORE_INSERT, BEFORE_UPDATE {
return 'Before save: records can still be edited';
}
when AFTER_INSERT, AFTER_UPDATE {
return 'After save: records are read-only, Ids exist';
}
when BEFORE_DELETE, AFTER_DELETE {
return 'Delete: only old values are available';
}
when AFTER_UNDELETE {
return 'Undelete: only new values are available';
}
when else {
return 'Not a trigger context';
}
}
}
}You can list several values after one when, separated by commas. The when else branch matters for one case. Outside a trigger, such as when a test calls the class directly, Trigger.operationType is null, and a switch on null goes to when else.
Casting to the concrete type
Trigger.new is a List<SObject>, even in an Account trigger. To read Account fields with normal dot syntax, cast it:
List<Account> newAccounts = (List<Account>) Trigger.new;
Map<Id, Account> oldAccounts = (Map<Id, Account>) Trigger.oldMap;Do this once, at the top of the handler, and pass the typed collections to the methods that do the work. The handler in the spine does this:
when BEFORE_UPDATE {
beforeUpdate((List<Account>) Trigger.new, (Map<Id, Account>) Trigger.oldMap);
}Passing the collections as parameters has two benefits. The methods are easy to call from a test with hand-built data, and each method signature states which values it needs.
Comparing old and new values
The most common use of oldMap is to find out which records actually changed. A trigger on update fires for every record in the batch, including records where nobody touched the field you care about. Without a check, you do work for all of them.
public with sharing class AccountChangeDetector {
public static List<Account> renamed(
List<Account> newAccounts,
Map<Id, Account> oldMap
) {
List<Account> changed = new List<Account>();
for (Account acc : newAccounts) {
Account previous = oldMap.get(acc.Id);
if (previous != null && acc.Name != previous.Name) {
changed.add(acc);
}
}
return changed;
}
}The loop is driven by newAccounts, and each record is matched to its old version by Id. The method makes no SOQL query and no DML call, so it is safe at 200 records. The previous != null check is defensive. In a real before update trigger it is always true, but it keeps the method safe if a caller passes a partial map.
Compare with != on values, not by identity. For text, number, date, and Id fields, != compares values. If the field can be null on either side, != still works, because null != 'A' is true and null != null is false.
Common errors
These are the mistakes that appear most often when people start reading context variables.
- Reading
oldMapin an insert.Trigger.oldMap.get(acc.Id)throws aNullPointerExceptioninBEFORE_INSERTandAFTER_INSERT, becauseoldMapisnullthere. Put old-value logic only in update methods, which theswitchonoperationTypemakes easy. - Using
Trigger.newMapin before insert. It isnull. UseTrigger.new. - Assigning fields in an after trigger.
acc.Description = 'x'on a record fromTrigger.newthrows aSystem.FinalException("Record is read-only"). Move the change to a before trigger, or update a separate copy of the record. - Looking only at
Trigger.new[0]. The trigger receives up to 200 records. Always loop over the whole collection. - Reading
Trigger.newin a delete. It isnull, so a loop over it throws aNullPointerException. UseTrigger.old. - Calling trigger variables from a plain test. If a test calls
new AccountTriggerHandler().run()directly, everyTrigger.*collection isnullandoperationTypeisnull. Test through DML instead, as a later chapter shows, or pass the collections in as method parameters.
Putting it together
The following handler reads the three main variables once, in run(), and hands typed collections to each method. It covers every operation with its own when branch, so none of the null cases from the table is reachable.
public with sharing class AccountTriggerHandler {
public void run() {
switch on Trigger.operationType {
when BEFORE_INSERT {
beforeInsert((List<Account>) Trigger.new);
}
when BEFORE_UPDATE {
beforeUpdate(
(List<Account>) Trigger.new,
(Map<Id, Account>) Trigger.oldMap
);
}
when BEFORE_DELETE {
beforeDelete((Map<Id, Account>) Trigger.oldMap);
}
when else {
// Other operations are not handled yet.
}
}
}
private void beforeInsert(List<Account> newAccounts) {
for (Account acc : newAccounts) {
if (String.isBlank(acc.Description)) {
acc.Description = 'Created without a description';
}
}
}
private void beforeUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
for (Account acc : newAccounts) {
if (acc.Name != oldMap.get(acc.Id).Name) {
acc.Description = 'Renamed from ' + oldMap.get(acc.Id).Name;
}
}
}
private void beforeDelete(Map<Id, Account> oldAccounts) {
for (Account acc : oldAccounts.values()) {
if (acc.Name == 'Protected') {
acc.addError('This account cannot be deleted.');
}
}
}
}addError on a record in a before delete blocks that record's deletion and shows the message to the user. It works on Trigger.old records even though their field values are read-only.
Summary of the working model
- The trigger runs once per batch of up to 200 records, and every context variable is a collection.
- Which variables are filled depends on the event. Insert and undelete have no old values, and delete has no new values.
Trigger.operationTypeis an enum, so aswitchon it is checked at compile time and handles the "not in a trigger" case throughwhen else.- Before triggers can change
Trigger.new. After triggers cannot. - Cast the collections once and pass them to methods as typed parameters.
Exercise
A handler's afterInsert method contains Account previous = (Account) Trigger.oldMap.get(acc.Id); inside a loop over Trigger.new. What happens when 200 accounts are inserted, and how do you fix it?
Show answer
The method throws a System.NullPointerException on the first record, because Trigger.oldMap is null in insert events (a new record has no previous version). The fix is to remove the old-value lookup from the insert method, since there is nothing to compare against. If the logic must compare old and new values, move it to a BEFORE_UPDATE or AFTER_UPDATE branch, where oldMap is populated and can be read with oldMap.get(acc.Id).
Exercise
Using only the table in this chapter, list which of Trigger.new, Trigger.newMap, Trigger.old, and Trigger.oldMap are null in an AFTER_DELETE event, and name the two variables you would use to read the deleted records.
Show answer
Trigger.new and Trigger.newMap are null, because deleted records have no new version. Trigger.old and Trigger.oldMap are populated, so you read the deleted records from either Trigger.old (a list) or Trigger.oldMap (a map keyed by Id).