switch statement and enums in trigger

In summer ’18 release switch statement and enums in trigger were introduced.For enums they introduced a new context variable called Trigger.operationType which has following values,

  • BEFORE_INSERT
  • AFTER_INSERT
  • BEFORE_UPDATE
  • AFTER_UPDATE
  • BEFORE_DELETE
  • AFTER_DELETE
  • AFTER_UNDELETE

If you combine this new Apex switch and enum new context variable  feature, trigger code will be easier to handle conditional checks.

switch on Trigger.operationType {
        
            when AFTER_INSERT, AFTER_UPDATE {
                //create related records
            }
            when BEFORE_INSERT {
                //set value on record create
            }
            when AFTER_DELETE {
                //prevent deletion of sensitive data
            }
            when else {
                //do nothing for AFTER_UNDELETE, BEFORE_DELETE, or BEFORE_UPDATE
            }
        }

Be the first to comment

Leave a Reply

Your email address will not be published.


*