Tag Archives: Trigger Handler

Salesforce Trigger Handler Patterns

To move all code from Trigger to Apex Classes(Handler Classes) is one of the Salesforce Best Practices. Here is an example to write Trigger Handler class.

Apex Trigger:

trigger objectTrigger on Object (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
    
    objectTriggerHandler handler = new objectTriggerHandler();
    
    //Before Insert
    if(Trigger.isInsert && Trigger.isBefore){
        handler.OnBeforeInsert(Trigger.new);
    }
    //After Insert
    else if(Trigger.isInsert && Trigger.isAfter){
        handler.OnAfterInsert(Trigger.new);
    }
    //Before Update
    else if(Trigger.isUpdate && Trigger.isBefore){
        handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap);
    }
    //After Update
    else if(Trigger.isUpdate && Trigger.isAfter){
        handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.newMap);
    }
    //Before Delete
    else if(Trigger.isDelete && Trigger.isBefore){
        handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);
    }
    //After Delete
    else if(Trigger.isDelete && Trigger.isAfter){
        handler.OnAfterDelete(Trigger.old, Trigger.oldMap);
    }
    //After Undelete
    else if(Trigger.isUnDelete){
        handler.OnUndelete(Trigger.new);
    }
}

Trigger Handler Apex Class:

public with sharing class ObjectTriggerHandler {
    
    private boolean isExecuting = false;
    
    public ObjectTriggerHandler(boolean isExecuting){
        this.isExecuting = isExecuting;
    }
    
    public void OnBeforeInsert(List<Object> newObjects){
        //EXECUTE BEFORE INSERT LOGIC
    }
    
    public void OnAfterInsert(List<Object> newObjects){
        //EXECUTE AFTER INSERT LOGIC
    }
    
    public void OnBeforeUpdate(List<Object> oldObjects, List<Object> updatedObjects, Map<Id, Object> ObjectMap){
        //BEFORE UPDATE LOGIC
    }
    
    public void OnAfterUpdate(List<Object> oldObjects, List<Object> updatedObjects, Map<Id, Object> ObjectMap){
        //AFTER UPDATE LOGIC
    }
    
    public void OnBeforeDelete(List<Object> ObjectsToDelete, Map<Id, Object> ObjectMap){
        //BEFORE DELETE LOGIC
    }
    
    public void OnAfterDelete(List<Object> deletedObjects, Map<Id, Object> ObjectMap){
        //AFTER DELETE LOGIC
    }
    
    public void OnUndelete(List<Object> restoredObjects){
        //AFTER UNDELETE LOGIC
    }
    
    public boolean IsTriggerContext{
        get{ return isExecuting;}
    }
}