Sub topic 4
What the Trigger class gives you
This chapter assumes you can write basic Apex (variables, loops, List, Set, Map), understand records and record Ids, and have used DML statements and SOQL. It also assumes you know that governor limits exist. It gives a map of the Trigger class. Later chapters cover the record collections, the availability rules and the flags in detail.
A trigger has no parameters
An Apex method receives its inputs as arguments. A trigger does not. Salesforce runs it with no arguments, and the platform exposes everything about the current invocation through a built-in class called Trigger. Its members are static, and the platform fills them in before your code runs. They are called context variables.
Every context variable answers one of three questions:
- Which records are involved? The record collections.
- Which event fired me? The Boolean flags and
operationType. - How much work is there?
Trigger.size.
The full list
| Variable | Type | What it tells you |
|---|---|---|
| `Trigger.new` | `List<SObject>` | The new versions of the records |
| `Trigger.old` | `List<SObject>` | The old versions of the records |
| `Trigger.newMap` | `Map<Id, SObject>` | The new versions, keyed by record Id |
| `Trigger.oldMap` | `Map<Id, SObject>` | The old versions, keyed by record Id |
| `Trigger.isInsert` | `Boolean` | True if the event is an insert |
| `Trigger.isUpdate` | `Boolean` | True if the event is an update |
| `Trigger.isDelete` | `Boolean` | True if the event is a delete |
| `Trigger.isUndelete` | `Boolean` | True if the event is an undelete |
| `Trigger.isBefore` | `Boolean` | True if the trigger runs before the save |
| `Trigger.isAfter` | `Boolean` | True if the trigger runs after the save |
| `Trigger.operationType` | `System.TriggerOperation` | An enum value naming the exact event |
| `Trigger.isExecuting` | `Boolean` | True if the current code is running in a trigger context |
| `Trigger.size` | `Integer` | The total number of records in this invocation |
The collections are typed as SObject, the generic parent of all record types. In a trigger on Account, the platform hands you Account records. Iterating with for (Account a : Trigger.new) works because Apex converts them for you. A cast is needed only when you work with the collection as a whole, for example when you pass it to a method that takes List<Account>.
Records: new, old and the map versions
Trigger.new and Trigger.old are lists. Trigger.newMap and Trigger.oldMap hold the same records indexed by Id, which is useful when you need to match a record to its counterpart. Two points matter now:
- The platform fills in only the collections that make sense for the event. A record that is being inserted has no old version, and a record that is being deleted has no new version. An unavailable collection is
null, not an empty list. CallingTrigger.new.size()in a delete trigger therefore throws aSystem.NullPointerException. - A record that has not been saved yet has no Id. The map versions need Ids, so they are absent in
before insert.
The chapter "Which variables exist in which event" gives the full table. For now, treat every collection as "might be null" until you know the event.
Events: flags and operationType
Seven events can fire a trigger: before insert, before update, before delete, after insert, after update, after delete and after undelete. Two groups of flags describe them:
isInsert,isUpdate,isDeleteandisUndeletename the operation.isBeforeandisAftername the timing.
You combine one from each group to identify the event. Trigger.isUpdate && Trigger.isBefore means before update. Exactly one operation flag is true in any invocation, and exactly one timing flag is true.
Trigger.operationType carries the same information in a single value of type System.TriggerOperation. Its values are BEFORE_INSERT, BEFORE_UPDATE, BEFORE_DELETE, AFTER_INSERT, AFTER_UPDATE, AFTER_DELETE and AFTER_UNDELETE. Because it is an enum, you can use it in a switch statement. A later chapter covers that.
Invocation: size and isExecuting
Trigger.size is the number of records in this invocation. For an update or insert it equals Trigger.new.size(). For a delete it equals Trigger.old.size(). Because it is an Integer and never null, it is the safe way to count records in any event.
Trigger.isExecuting is true when the current code was reached through a trigger. In a trigger body it is always true, so checking it there adds nothing. Its value is in helper classes that can be called from many places. A method that runs from an anonymous Apex window or a test sees false.
See the context for yourself
The following trigger logs every context variable that is safe to read in every event. Save it and then insert, update, delete and undelete an Account to see how the output changes.
trigger AccountContextLogger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
System.debug('operationType: ' + Trigger.operationType);
System.debug('isExecuting: ' + Trigger.isExecuting);
System.debug('isBefore: ' + Trigger.isBefore + ', isAfter: ' + Trigger.isAfter);
System.debug('isInsert: ' + Trigger.isInsert
+ ', isUpdate: ' + Trigger.isUpdate
+ ', isDelete: ' + Trigger.isDelete
+ ', isUndelete: ' + Trigger.isUndelete);
System.debug('size: ' + Trigger.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));
}Comparing a collection with null is safe. Reading .size() on it is not. In the debug log for before insert, you will see new is not null and old, newMap and oldMap are null. On after delete, only old and oldMap are populated. You will fill in the rest of this pattern in the next chapters.
Remove this trigger when you are done. It runs on every Account change in the org.
Context variables belong to the trigger transaction
The Trigger class has three consequences that cause real bugs.
Values are fixed for each invocation
The platform sets the variables when it starts your trigger, and they describe that one batch. If the trigger performs DML that causes another trigger invocation, the nested invocation gets its own context. When it finishes, your outer variables are as they were.
Batches hold up to 200 records
Salesforce processes records in chunks. When a single operation touches more than 200 records, such as a data load of 1,000 Accounts, the platform calls the trigger once per chunk of up to 200, within the same transaction. Trigger.size is therefore at most 200 for each call. Write the code as though it will always receive a list, even when you expect one record. The chapter on bulk-safe logic builds on this.
Helper classes can see Trigger too
A static class can read Trigger.new from any code that runs inside a trigger transaction. That looks convenient. It makes the class hard to test, because outside a trigger context, including in a test method that calls the helper directly, Trigger.new is null. Pass what the helper needs as arguments:
public class AccountDescriptionHelper {
public static void setDefaults(List<Account> accounts) {
for (Account a : accounts) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by helper';
}
}
}
}
trigger AccountDefaults on Account (before insert) {
AccountDescriptionHelper.setDefaults(Trigger.new);
}setDefaults can now be tested with a list you build yourself. The handler class chapter develops this approach.
Common mistakes
- Assuming
Trigger.newalways exists. It isnullin delete events. - Counting with
Trigger.new.size(). UseTrigger.size. It works in every event. - Treating
isBeforeas the operation.isBeforeandisAftersay when the trigger runs. They do not say what happened. Always pair them with an operation flag or useoperationType. - Using
isExecutingas a branch inside a trigger. It is always true there. Use it in code shared between triggers and other callers. - Reaching for
Triggerinside a utility class. Pass the lists in instead.
Exercise
A single trigger is declared on Contact for before delete and after delete. A developer writes Integer count = Trigger.new.size(); as the first line. What happens when a Contact is deleted, and what should the line be?
Show answer
Delete events have no new versions of the records, so Trigger.new is null. Calling .size() on it throws a System.NullPointerException. Use Trigger.size, which is set for every event, or use Trigger.old.size() for delete events.
Exercise
Which two context variables would you check together to tell a before update from an after update, and which single variable gives the same answer?
Show answer
Check Trigger.isBefore (or Trigger.isAfter) together with Trigger.isUpdate. The single variable is Trigger.operationType, which returns System.TriggerOperation.BEFORE_UPDATE or System.TriggerOperation.AFTER_UPDATE.