Trigger Handler Pattern in Salesforce

Trigger Handler Pattern in Salesforce

Following is the syntax for sample Trigger Handler Pattern in Salesforce.

Trigger:
trigger OpportunityTrigger on Opportunity(before insert, before update, after insert, after update ) {
    
    if ( trigger.isBefore ) {
    
        if ( trigger.isInsert ) {
        
            OpportunityHandlerController.onBeforeInsert(trigger.new);
            
        } else if ( trigger.isUpdate ) {
        
            OpportunityHandlerController.onBeforeUpdate(trigger.new, trigger.oldMap);
            
        } else if ( trigger.isDelete ) {
        
            OpportunityHandlerController.onBeforeDelete(trigger.old, trigger.oldMap);
            
        }
                    
    } else if ( trigger.isAfter ) {
    
        if ( trigger.isInsert ) {
        
            OpportunityHandlerController.onAfterInsert(trigger.new);
            
        } else if ( trigger.isUpdate ) {
        
            OpportunityHandlerController.onAfterUpdate(trigger.new, trigger.oldMap);
            
        }
        else if ( trigger.isDelete ) {
        
            OpportunityHandlerController.onAfterDelete(trigger.old, trigger.oldMap);
            
        }
                    
    }
    
}
Apex Controller:
public class OpportunityHandlerController {
    
    public static void onBeforeInsert( List < Opportunity > OpportunityList ) {
        /*
call before insert actions
*/
    }
    
    public static void onBeforeUpdate( List < Opportunity > OpportunityList, Map < Id, Opportunity > mapOpptyOld ) {
        /*
        call before update actions
        */
    }
    
    public static void onBeforeDelete( List < Opportunity > OpportunityList, Map < Id, Opportunity > mapOpptyOld) {
        /*
        call before delete actions
        */
    }
    
    public static void onAfterInsert( List < Opportunity > OpportunityList ) {
        /*
        call after insert actions
        */
    }
    
    public static void onAfterUpdate( List< Opportunity > OpportunityList, Map< Id, Opportunity > mapOpptyOld ) {
        /*
        call after update actions
        */
    }
    
    public static void onAfterDelete( List < Opportunity > OpportunityList, Map < Id, Opportunity > mapOpptyOld ) {
        /*
        call after delete actions
        */
    }
    
}

Leave a Reply