Trigger Logic with Apex Switch

Switch Statements

Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly.

Switch Statements

Rethink Trigger Logic with Apex Switch
Trigger Context Variables

The context variable Trigger.operationType is used to get the current System.TriggerOperation enum value.

The following are the values of the System.TriggerOperation enum:

AFTER_DELETE
AFTER_INSERT
AFTER_UNDELETE
AFTER_UPDATE
BEFORE_DELETE
BEFORE_INSERT
BEFORE_UPDATE

trigger customerTrigger on Account (before insert, after insert) {

    switch on Trigger.operationType {
        when BEFORE_INSERT {
            System.debug('Before Insert');
        }
        when AFTER_INSERT {
            System.debug('After Insert');
        }
        when else {
            System.debug('Something went wrong');
        }
    }
}

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach