Sub topic 7
Dispatching to before and after methods
This chapter assumes you can read basic Apex (classes, methods, collections), know the DML operations, and have seen the logic-less trigger from the previous chapters. Here you will route each trigger event to its own handler method.
Why dispatch at all
The trigger from the last chapter subscribes to all seven events and calls run(). A before-insert and an after-delete have different rules, so they should not share one block of code. The handler's run() method sorts the events and sends each to a method with a clear purpose.
Switching on Trigger.operationType
Trigger.operationType returns a value of the System.TriggerOperation enum, such as BEFORE_INSERT or AFTER_UNDELETE. A switch on statement matches the enum value directly. Compare this with the older approach of nested if (Trigger.isBefore && Trigger.isInsert) checks, which is longer and easier to get wrong.
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 AFTER_INSERT {
afterInsert((List<Account>) Trigger.new);
}
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 afterInsert(List<Account> newAccounts) {
List<Task> followUps = new List<Task>();
for (Account acc : newAccounts) {
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps; // one DML statement for the whole batch
}
}Two details matter here:
Trigger.newis typed asList<SObject>. The cast toList<Account>gives the methods typed fields such asacc.Description.- The
when elsebranch makes unhandled events explicit. The trigger still subscribes to delete and undelete, but nothing happens until you add awhenbranch for them.
What each phase lets you do
The method name tells you which rules apply.
| Method | Record Ids | Change the triggering records | Typical use |
|---|---|---|---|
| `beforeInsert` | Not assigned yet | Yes, by setting fields | Defaults, validation |
| `beforeUpdate` | Present | Yes, by setting fields | Derived fields, change checks |
| `afterInsert` | Assigned | No, they are read-only | Creating related records |
In beforeInsert and beforeUpdate, you change the records by assigning fields. Salesforce saves them afterward, so you must not run DML on them. In afterInsert, the records already have Ids, which is why the Task can point at acc.Id.
Common errors
- Using
Trigger.oldMapin an insert. It isnullfor insert events. Pass it only to update and delete methods. - Using
Trigger.newin a delete. It isnullfor delete events. UseTrigger.oldinstead. - Reading
acc.IdinbeforeInsert. It isnullbecause the record is not saved yet. - Calling
updateonTrigger.newin a before method. This fails or causes needless work. Set the fields and return. - Editing records in an after method.
Trigger.newis read-only there. Query fresh copies or build new records.
Exercise
You add a when AFTER_UPDATE branch to run() that calls afterUpdate(Trigger.new, Trigger.oldMap). The method needs to compare old and new values of Name. Which cast do you apply to each argument, and why is Trigger.old or Trigger.oldMap safe to use here but not in beforeInsert?
Show answer
Cast Trigger.new to List<Account> and Trigger.oldMap to Map<Id, Account>. Update events carry the previous version of each record, so oldMap is populated. In an insert there is no previous version, so oldMap is null.