Sub topic 13
Switching on Trigger.operationType
This chapter assumes you can write a basic Apex trigger and know the seven trigger events. It also assumes you know which of Trigger.new, Trigger.old, Trigger.newMap and Trigger.oldMap exist in each event, and that you can read Trigger.isInsert and Trigger.isBefore. You should also be comfortable with Apex switch statements and enums.
What Trigger.operationType returns
Trigger.operationType returns a value of the enum System.TriggerOperation. The enum has one value for each of the seven trigger events:
| Enum value | Fires when |
|---|---|
| `BEFORE_INSERT` | Before new records are saved |
| `BEFORE_UPDATE` | Before changes to existing records are saved |
| `BEFORE_DELETE` | Before records are deleted |
| `AFTER_INSERT` | After new records are saved |
| `AFTER_UPDATE` | After changes are saved |
| `AFTER_DELETE` | After records are deleted |
| `AFTER_UNDELETE` | After records are restored from the Recycle Bin |
Each value combines the timing (before or after) and the DML operation. With the Boolean flags you test two properties, such as Trigger.isBefore && Trigger.isInsert. With operationType you test one value that already holds both.
Why use a switch instead of if statements
A trigger that handles several events often ends up with nested conditions:
if (Trigger.isBefore) {
if (Trigger.isInsert) {
// ...
} else if (Trigger.isUpdate) {
// ...
}
} else if (Trigger.isAfter) {
if (Trigger.isInsert) {
// ...
}
}A switch on the enum is flatter. Each event gets one when branch, and you can read the whole list of supported events at a glance. The compiler also checks the enum value names. If you misspell BEFORE_UPDTE, the code won't compile. A misspelled string comparison would compile and silently never match.
A complete example
The trigger below handles five events on Contact. It does no real work itself and only routes each event to a method in a handler class.
trigger ContactTrigger on Contact (
before insert, before update, before delete,
after insert, after undelete
) {
switch on Trigger.operationType {
when BEFORE_INSERT, BEFORE_UPDATE {
ContactHandler.normalizeEmails(Trigger.new);
}
when BEFORE_DELETE {
ContactHandler.blockPrimaryContactDeletes(Trigger.old);
}
when AFTER_INSERT {
ContactHandler.createWelcomeTasks(Trigger.new);
}
when AFTER_UNDELETE {
ContactHandler.createRestoreTasks(Trigger.new);
}
when else {
System.debug('Unhandled operation: ' + Trigger.operationType);
}
}
}The handler class holds the logic. Each method takes a list, so it works for up to 200 records per batch:
public class ContactHandler {
public static void normalizeEmails(List<Contact> newContacts) {
for (Contact c : newContacts) {
if (c.Email != null) {
c.Email = c.Email.trim().toLowerCase();
}
}
}
public static void blockPrimaryContactDeletes(List<Contact> oldContacts) {
for (Contact c : oldContacts) {
if (c.Title == 'Primary Contact') {
c.addError('Primary contacts cannot be deleted.');
}
}
}
public static void createWelcomeTasks(List<Contact> newContacts) {
List<Task> tasks = new List<Task>();
for (Contact c : newContacts) {
tasks.add(new Task(
Subject = 'Send welcome email',
WhoId = c.Id
));
}
insert tasks;
}
public static void createRestoreTasks(List<Contact> restoredContacts) {
List<Task> tasks = new List<Task>();
for (Contact c : restoredContacts) {
tasks.add(new Task(
Subject = 'Review restored contact',
WhoId = c.Id
));
}
insert tasks;
}
}Each method matches the rules for its event:
normalizeEmailschanges field values onTrigger.newin a before event. No DML is needed.blockPrimaryContactDeletesreadsTrigger.old, because delete events have noTrigger.new.createWelcomeTasksruns after insert, when record Ids exist, and uses oneinsertoutside the loop.createRestoreTasksreadsTrigger.new, which is available inafter undelete.
Syntax rules for switch on an enum
Several details of the Apex switch statement matter here:
- Write the enum values without a prefix. Use
when BEFORE_INSERT, notwhen System.TriggerOperation.BEFORE_INSERT. - Combine values with commas in one
when, as inwhen BEFORE_INSERT, BEFORE_UPDATE. Use this when two events share logic. - A value can appear in only one
whenclause of a switch. when elseruns for any value not matched earlier. It must come last.- There is no fall-through. Only the matching block runs, so you don't write
break.
The diagram: how one trigger routes events
Sharing a branch and still telling events apart
Sometimes insert and update share most of the logic but differ in one step. Group them in one when, then use a Boolean flag for the small difference:
trigger LeadTrigger on Lead (before insert, before update) {
switch on Trigger.operationType {
when BEFORE_INSERT, BEFORE_UPDATE {
for (Lead l : Trigger.new) {
if (String.isBlank(l.Company)) {
l.Company = 'Unknown';
}
if (Trigger.isUpdate) {
Lead oldLead = Trigger.oldMap.get(l.Id);
if (l.Status != oldLead.Status) {
l.Description = 'Status changed from '
+ oldLead.Status + ' to ' + l.Status;
}
}
}
}
when else {
System.debug('Unexpected operation: ' + Trigger.operationType);
}
}
}The Trigger.isUpdate check matters. Trigger.oldMap is null on insert, so calling Trigger.oldMap.get(...) there throws a NullPointerException. The flags and operationType are not rivals. Use the switch to choose the branch and the flags for small differences inside one.
Boolean flags or operationType
| Situation | Better choice |
|---|---|
| Trigger handles one or two events | Boolean flags are short enough |
| Trigger handles many events with different logic | `switch` on `operationType` |
| You want to pass the current event to another class | `operationType`, because it is one value |
| You only need "any before" or "any after" logic | `Trigger.isBefore` or `Trigger.isAfter` |
Because operationType is an ordinary enum value, you can pass it as a method parameter. A handler method can then take a System.TriggerOperation argument and run its own switch. Passing four separate Booleans is clumsier and easier to get wrong.
Common errors
Declaring fewer events than the switch handles. The event list on the trigger line decides which events fire the trigger. If the trigger header lists before insert only, a when AFTER_INSERT branch never runs. No error is shown. Keep the header and the switch in sync.
Forgetting when else. Without it, an event you don't handle is silently skipped. That is fine if you declared only the events you handle. If someone later adds an event to the header and forgets the switch, the missing branch goes unnoticed. A when else that logs, or throws an exception, makes the gap visible.
Reading a null collection. The switch tells you which event you are in, but you still need to pick the right variable. In BEFORE_DELETE and AFTER_DELETE, Trigger.new is null. In BEFORE_INSERT, Trigger.old and Trigger.oldMap are null. In BEFORE_INSERT, Trigger.newMap is also null, because records have no Ids yet.
Doing DML on the wrong side of the timing line. BEFORE_* branches can change Trigger.new directly. AFTER_* branches cannot, because those records are read-only. Putting field edits in an AFTER_INSERT branch causes a runtime error.
Putting everything in the trigger body. A switch with large when blocks is hard to read and test. Keep each when to one handler call, as in the first example.
Exercises
Exercise
A trigger on Opportunity is declared as trigger OppTrigger on Opportunity (before insert, after update). Its switch has branches for BEFORE_INSERT, BEFORE_UPDATE and AFTER_UPDATE. Which branches can run, and what should you change?
Show answer
Only BEFORE_INSERT and AFTER_UPDATE can run, because those are the events in the trigger header. The BEFORE_UPDATE branch never runs and gives no error. Either add before update to the header so the branch is used, or remove the dead branch.
Exercise
In a when BEFORE_INSERT, BEFORE_UPDATE branch, you write Trigger.oldMap.get(rec.Id) for each record in Trigger.new. What goes wrong on insert, and how do you fix it?
Show answer
Trigger.oldMap is null on insert, so the call throws a NullPointerException. Wrap the lookup in if (Trigger.isUpdate), or split the two events into separate when branches.
Exercise
Write a switch on Trigger.operationType that calls Handler.onDelete(Trigger.old) for both BEFORE_DELETE and AFTER_DELETE, and does nothing for any other value.
Show answer
switch on Trigger.operationType { when BEFOREDELETE, AFTERDELETE { Handler.onDelete(Trigger.old); } when else { } }