10

A new enum TriggerOperation is documented but no corresponding variable has been added to the Trigger Context Variables documentation. I've just found out that using API 43.0, a reference to Trigger.Operation (see idea link immediately below) won't compile.

The idea A Trigger Context Enum to represent the current operation and before/after state that includes this example - the example not provided by Salesforce mind you - is marked as "delivered":

switch on Trigger.Operation {
    when TriggerOperation.BEFORE_INSERT, TriggerOperation.BEFORE_UPDATE { /* stuff */ }
    where TriggerOperation.AFTER_INSERT { /* ... */ }
}

Anyone have any idea if Trigger.Operation or an equivalent will make an appearance in the near future?

It's not rocket science to write code to return the TriggerOperation enum value, it's just a shame if everyone has to write and test their own given that it's behaviour that belongs in Trigger:

public static TriggerOperation operation() {
    if (Trigger.isBefore) {
        if (Trigger.isUpdate) return TriggerOperation.BEFORE_UPDATE;
        else if (Trigger.isInsert) return TriggerOperation.BEFORE_INSERT;
        else if (Trigger.isDelete) return TriggerOperation.BEFORE_DELETE;
    } else if (Trigger.isAfter) {
        if (Trigger.isUpdate) return TriggerOperation.AFTER_UPDATE;
        else if (Trigger.isInsert) return TriggerOperation.AFTER_INSERT;
        else if (Trigger.isDelete) return TriggerOperation.AFTER_DELETE;
        else if (Trigger.isUndelete) return TriggerOperation.AFTER_UNDELETE;
    }
    return null;
}
7

You can use the context variable Trigger.operationType to get current System.TriggerOperation enum value.

To test it with switch, you can use something like this.

trigger TestSwitch 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');
        }
    }
}

Sample example with handler class can be found in Salesforce developer blogs

P.S. unfortunately, official documentation is yet not updated with enum context variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.