How to use Trigger.operationType in Salesforce Trigger?

How to use Trigger.operationType in Salesforce Trigger?

Switch statement should be utilised to use Trigger.operationType in Salesforce Trigger.

Trigger operationType in the Salesforce Trigger avoids multiple if else conditions to check trigger.isInsert, trigger.isUpdate, trigger.isBefore, trigger.isAfter, etc..

Sample Code:

trigger AccountTrigger on Account( before insert, after insert, before update, after update ) {
    
    switch on Trigger.operationType {
    
        when BEFORE_INSERT {
            System.debug( 'Before Insert' );
        }
    
        when AFTER_INSERT {
            System.debug( 'After Insert' );
        }
    
        when BEFORE_UPDATE {
            System.debug( 'Before Update' );
        }
    
        when AFTER_UPDATE {
            System.debug( 'After Update' );
        }
    
    }
    
}

Sample Code to check insert operation:

insert new Account(
    Name = 'Testing'
);

Sample Code to check update operation:

update new Account(
    Id = '0018c00002RqtPVAAZ',
    Description = 'Testing'
);

Leave a Reply