ApexSensei

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:

  1. Add before update to the trigger events, next to before insert.
  2. Pick a branch with switch on Trigger.operationType (or Trigger.isInsert and Trigger.isUpdate).
  3. On insert, call the handler's beforeInsert with Trigger.new.
  4. On update, call the handler's beforeUpdate with Trigger.new and Trigger.oldMap.
  5. 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.

Try this drill free

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 ›