Drills › Automate with triggers
Route Case trigger contexts
Automate with triggers · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Scenario. Case creation and Case status changes need different automation, but the team wants one small trigger as the entry point.
Add the update event to a Case trigger and use Trigger.operationType to send inserts and updates to the right handler method.
What you will learn
One trigger can handle several events. Trigger.operationType tells you which event is running, and switch on picks the matching branch.
switch on Trigger.operationType {
when AFTER_INSERT {
Handler.afterInsert(Trigger.new);
}
}
Trigger.isInsert and Trigger.isUpdate work too, inside if checks.
Gotcha. Trigger.oldMap is null on insert. Use it only in update branches.
The task
Finish the Case trigger so inserts and updates each call the matching method on the provided handler.
Examples:
- insert with a blank Description →
Created by trigger - update Status
New→Closed→Status: New -> Closed - update the Subject only → Description stays the same
Requirements:
- Add
before updateto the trigger events, next tobefore insert. - Pick a branch with
switch on Trigger.operationType(orTrigger.isInsertandTrigger.isUpdate). - On insert, call the handler's
beforeInsertwithTrigger.new. - On update, call the handler's
beforeUpdatewithTrigger.newandTrigger.oldMap. - Pass the whole lists and do no DML in the trigger.
Starter code
trigger AS_879FDC3DCD3B_CaseContexts on Case (before insert) {
}
When it passes
New Cases get their default, Status changes are logged, other edits are left alone, and 200-record inserts and updates each reach the handler in full.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ React to a Contact email change · Mark parent Accounts in bulk ›