Sub topic 2
Reading Trigger.new, Trigger.oldMap and Trigger.operationType
This chapter assumes you can write basic Apex (classes, methods, collections). It also assumes you know the DML operations (insert, update, delete, undelete) and have heard of governor limits. Here you learn which context variables a trigger gets and how to read them safely.
What context variables are
Inside a trigger, Salesforce gives you static variables on the Trigger class. They describe the records being saved and the operation that caused the trigger to run. You never declare them. They exist only while a trigger is executing.
The three you use most are:
Trigger.newis aList<SObject>of the records with their new values.Trigger.oldMapis aMap<Id, SObject>of the records as they were before the change, keyed by record Id.Trigger.operationTypeis aSystem.TriggerOperationenum value that names the event, such asBEFORE_INSERTorAFTER_UPDATE.
Which variables exist in which event
Not every variable is available in every event. Reading one that is not set gives you null, and using that value causes a NullPointerException.
| Event | Trigger.new | Trigger.oldMap | Notes |
|---|---|---|---|
| before insert | Yes, editable | null | Records have no Id yet. |
| after insert | Yes, read-only | null | Records now have Ids. |
| before update | Yes, editable | Yes | Compare new and old values. |
| after update | Yes, read-only | Yes | Use for work on related records. |
| before delete | null | Yes | Records are still in the database. |
| after delete | null | Yes | Records are gone. |
| after undelete | Yes, read-only | null | Records are restored. |
In a before event you can change field values on Trigger.new directly. Salesforce saves your changes, so no DML statement is needed. In an after event the records are read-only, and changing them throws an error.
Casting to a concrete type
Trigger.new is typed as List<SObject>. To read fields such as Name, cast it to the concrete type. Do the same for Trigger.oldMap.
List<Account> newAccounts = (List<Account>) Trigger.new;
Map<Id, Account> oldAccounts = (Map<Id, Account>) Trigger.oldMap;Do the cast once, at the top of the method that uses it. Passing typed collections into your handler methods keeps the rest of the code free of casts.
Comparing new and old values
In an update, look up the old record by Id and compare the field you care about. This is how you react only to real changes.
for (Account acc : (List<Account>) Trigger.new) {
Account oldAcc = ((Map<Id, Account>) Trigger.oldMap).get(acc.Id);
if (acc.Name != oldAcc.Name) {
acc.Description = 'Renamed from ' + oldAcc.Name;
}
}The map lookup is cheap and uses no SOQL query. Never query the database to fetch old values, because Trigger.oldMap already holds them.
Reading the operation type
One trigger usually subscribes to several events. Trigger.operationType tells you which one fired. Use a switch statement on the enum, which is clearer than testing several booleans such as Trigger.isBefore and Trigger.isInsert.
switch on Trigger.operationType {
when BEFORE_INSERT {
System.debug('Before insert for ' + Trigger.new.size() + ' records');
}
when AFTER_UPDATE {
System.debug('After update for ' + Trigger.new.size() + ' records');
}
when else {
System.debug('Not handled: ' + Trigger.operationType);
}
}The when else branch makes it explicit that unhandled events are ignored on purpose.
Common errors
- Reading
Trigger.oldMapin an insert. It isnull, so.get()fails. Check the operation first. - Reading
Trigger.newin a delete. It isnull, so useTrigger.oldorTrigger.oldMap. - Using
Trigger.new.get(0)and ignoring the rest. A trigger receives up to 200 records per batch, so always loop. - Writing to
Trigger.newfields in an after event. This throws a "read-only" error. Do the change in a before event instead.
Exercise
A trigger on Account runs on after delete. A developer writes for (Account a : (List<Account>) Trigger.new). What happens, and how do you fix it?
Show answer
In an after delete event, Trigger.new is null, so the loop throws a NullPointerException. Loop over (List<Account>) Trigger.old, or over the values of (Map<Id, Account>) Trigger.oldMap, instead.
Exercise
In a before update trigger, how do you set a field on each record without writing a DML statement, and why does that work?
Show answer
Assign the field directly on each record in Trigger.new. In a before event, Salesforce saves those changes as part of the original operation, so an extra update statement is not needed.