Sub topic 5
Trigger.new, Trigger.old and their map versions
This chapter assumes you can read basic Apex (loops, List, Set, Map), know what a record Id is, and have written simple SOQL and DML. It also assumes you know that governor limits cap queries and DML per transaction.
Every trigger receives its records through four context variables: Trigger.new, Trigger.old, Trigger.newMap and Trigger.oldMap. Picking the right one, and knowing when it is null, accounts for most beginner trigger bugs.
The four variables
| Variable | Type | Holds |
|---|---|---|
| `Trigger.new` | `List<SObject>` | The new versions of the records |
| `Trigger.old` | `List<SObject>` | The versions from before the change |
| `Trigger.newMap` | `Map<Id, SObject>` | The new versions, keyed by record Id |
| `Trigger.oldMap` | `Map<Id, SObject>` | The old versions, keyed by record Id |
"New" means the values being saved. "Old" means the values currently stored in the database. Each variable holds up to 200 records, because Salesforce passes records to a trigger in batches of at most 200.
The lists are typed as the generic SObject. In a trigger on Account, a for (Account a : Trigger.new) loop converts each element for you. The maps need an explicit cast if you want a typed map:
Map<Id, Account> oldAccounts = (Map<Id, Account>) Trigger.oldMap;You can also assign a single value from the map to a specific type, as in Account oldAcc = (Account) Trigger.oldMap.get(id);.
Where each variable exists
The next chapter covers availability by event in full. The rules that matter for this chapter are:
Trigger.newexists for insert, update and undelete. It is null for delete.Trigger.oldexists for update and delete. It is null for insert and undelete.Trigger.newMapneeds Ids. Records in a before insert trigger have no Id yet, soTrigger.newMapis null there. It exists in before update, after insert, after update and after undelete.Trigger.oldMapexists for update and delete.
Looping over a null list throws a NullPointerException. If one trigger handles several events, check the event first, or the variable you loop over may be null.
Modifiability
Trigger.old and Trigger.oldMap are always read-only. They describe history, and you cannot change it.
Trigger.new is editable only in before triggers. Changes you make to its records are saved with the original operation, so no DML statement is needed. In an after trigger the records are already saved, and an attempt to change a field on Trigger.new fails with a "Record is read-only" error. To change those records in an after trigger, query or construct separate records and run DML on them.
trigger AccountDescription on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountDescription';
}
}
}This works in both events because Trigger.new exists in both and is editable in both.
Why the maps exist
In an update trigger you often need the old version of the record you are looking at. The tempting approach is to use the same index in both lists:
// Fragile: do not rely on matching positions.
for (Integer i = 0; i < Trigger.new.size(); i++) {
Account newAcc = (Account) Trigger.new[i];
Account oldAcc = (Account) Trigger.old[i];
}Salesforce does not promise that the two lists line up by position in every case. The Id is the stable link between versions, so use the map instead:
trigger AccountPhoneTrigger on Account (before update) {
Map<Id, Account> oldAccounts = (Map<Id, Account>) Trigger.oldMap;
for (Account acc : Trigger.new) {
Account oldAcc = oldAccounts.get(acc.Id);
if (acc.Phone != oldAcc.Phone) {
acc.Description = 'Phone changed from ' + oldAcc.Phone;
}
}
}The loop walks the new records and looks up each one's old version by Id. The lookup cost is constant per record, and it stays correct whatever order the lists are in.
This code assumes an update. If you register the same trigger for before insert, Trigger.oldMap is null and oldAccounts.get(...) throws. Guard it with Trigger.isUpdate, which the chapter on boolean context flags covers.
Maps as sources of Ids for SOQL
The second use of the maps is feeding queries. Trigger.newMap.keySet() and Trigger.oldMap.keySet() return a Set<Id> of every record in the batch. Bind that set to a query once, outside any loop:
trigger AccountContactSync on Account (after update) {
List<Contact> contacts = [
SELECT Id, AccountId, MailingCountry
FROM Contact
WHERE AccountId IN :Trigger.newMap.keySet()
];
List<Contact> toUpdate = new List<Contact>();
for (Contact c : contacts) {
Account acc = (Account) Trigger.newMap.get(c.AccountId);
if (acc.BillingCountry != null && c.MailingCountry != acc.BillingCountry) {
c.MailingCountry = acc.BillingCountry;
toUpdate.add(c);
}
}
update toUpdate;
}One query covers up to 200 accounts, and Trigger.newMap.get(c.AccountId) connects each child back to its parent without a nested loop. One DML statement saves the changes. This is the bulk-safe shape: a query before the loop, work inside it, and DML after it.
The same pattern works for deletes, where the only Ids available are the old ones. In the next trigger, Trigger.oldMap.keySet() feeds the query, and Trigger.old supplies the records to reject:
trigger AccountDeleteCheck on Account (before delete) {
Set<Id> accountsWithOpenWork = new Set<Id>();
for (AggregateResult ar : [
SELECT AccountId
FROM Opportunity
WHERE AccountId IN :Trigger.oldMap.keySet() AND IsClosed = false
GROUP BY AccountId
]) {
accountsWithOpenWork.add((Id) ar.get('AccountId'));
}
for (Account acc : Trigger.old) {
if (accountsWithOpenWork.contains(acc.Id)) {
acc.addError('Close open opportunities before deleting this account.');
}
}
}Common errors
- Using
Trigger.newin a delete trigger. It is null, so the loop throwsNullPointerException. ReadTrigger.oldinstead. - Using
Trigger.newMapin before insert. Records have no Ids yet, so the map is null. Loop overTrigger.newand use fields on the record. - Editing
Trigger.newin an after trigger. The records are read-only after the save. Move the logic to a before trigger, or run DML on separate records. - Matching old and new by list index. Look up by Id through
Trigger.oldMapinstead. - Forgetting the cast.
Map<Id, Account> m = Trigger.oldMap;does not compile. Write(Map<Id, Account>) Trigger.oldMap. - Calling
Trigger.oldMap.get(id)for a record that was not in the batch. It returns null, and reading a field from null throws. Ids fromTrigger.newin an update are always present inTrigger.oldMap, but Ids from other queries are not.
Quick reference
- Walk the changing records with
Trigger.new, or withTrigger.oldfor deletes. - Compare versions with
Trigger.oldMap.get(record.Id). - Feed SOQL with
Trigger.newMap.keySet()orTrigger.oldMap.keySet(). - Edit fields on
Trigger.newonly in before triggers.
Exercise
A trigger on Opportunity is registered for before insert and before update. It loops over Trigger.new and calls Trigger.oldMap.get(opp.Id).StageName. It works when you edit an opportunity but fails when you create one. Why, and how do you fix it?
Show answer
In a before insert, Trigger.oldMap is null (and the new records have no Id yet), so calling get on it throws a NullPointerException. Guard the lookup with Trigger.isUpdate, or check that Trigger.oldMap is not null, and only compare StageName against the old record in the update case. In the insert case, use the new record's own fields.
Exercise
You write an after update trigger on Account that sets a.Description = 'Reviewed' for each record in Trigger.new. What happens, and where should the logic go instead?
Show answer
The save fails with a "Record is read-only" error, because records in Trigger.new cannot be edited in an after trigger. Move the assignment to a before update trigger, where changes to Trigger.new are saved automatically with no DML statement.