Handler & Dispatcher in Apex Triggers?

So far in the previous blogs/videos we have only talked about how to write the apex trigger and we have developed all the code inside the apex trigger.

However, as a best practice, we should not write the code inside Apex Trigger in this blog/video, we will convert the previous triggers to use the concept of Handler and Dispatcher class with Apex Trigger.

Table of Contents

Introduction

In this video, we will convert all the previous apex triggers with dispatcher and handler classes along with the helper class.

What is dispatcher class in Salesforce?

Let’s take an example for understanding the dispatcher class. It is like a courier system that will receive parcels from various vendors and will dispatch them to the customers.

In the same way the dispatcher class will receive the event from an Apex Trigger and then will route to correct Handler Class from the Dispatcher Class.

Example

trigger AccountTrigger on Account (before insert, before update, after insert, after update, after delete, before delete, after undelete) {
    AccountTriggerDispatcher.dispatch(Trigger.OperationType);
}

Introduction to Handler Class

Handler Classes are like courier persons who will be delivering the items to the customer at their address. In a similar way, the Handler Class will have multiple methods that will be responsible for performing the business functionality.

Below the code for the apex triggers that we have converted to Dispatcher, Handler & Helper Class.

Hands-On

Apex Trigger

trigger AccountTrigger on Account (before insert, before update, after insert, after update, after delete, before delete, after undelete) {
AccountTriggerDispatcher.dispatch(Trigger.OperationType);
}

Handler Class

public class AccountTriggerHandler {
    // before insert
    public static void handleBeforeInsert(List<Account> accountList){
        AccountTriggerHelper.updateAccountShippingAddress(accountList);       
    }
    // before update
    public static void handleBeforeUpdate(List<Account> accountList){
        AccountTriggerHelper.updateAccountShippingAddress(accountList);
    }
    // after insert
    public static void handleAfterInsert(List<Account> accountList){
        /*
            When the Account is Created,
            Create a Task Record under that Account and assign the Task to the Account Owner.
            Use the below information
            * Subject - Created from Apex Trigger
            * Description - Created from Apex Trigger
            * Due Date - Todays Date + 7
            * Status - Not Started
            * Priority - High
            * OwnerId - Account OwnerId
            * WhatId - Account.Id
        */
        /* Sub-Problems */
        // 1. Check if the code is running after insert
        // Do not make any DML withing for loop ( LIMIT - 150 ~ 151 )
        // Do not make any SOQL withing for loop ( LIMIT - 100 ~ 101 )
        
        List<Task> taskRecordToInsertList = new List<Task>();
          for(Account acc : accountList){ // Trigger.size = 200
            // Prepare Task Record
            Task t = new Task();
            t.Subject = 'Created from Apex Trigger';  
            t.Description = 'Created from Apex Trigger';
            t.Status = 'Not Started';
            t.Priority = 'High';
            t.ActivityDate = System.today().addDays(7);
            t.WhatId = acc.Id;
            t.OwnerId = acc.OwnerId;
            taskRecordToInsertList.add(t);
        }  
        // insert Task Record
        insert taskRecordToInsertList;
        // 200 times
    }
    // after update
    public static void handleAfterUpdate(){
        
    }
    
    
}

Helper Class

public class AccountTriggerHelper {

    // reusable methods - focus
    // further processing
    // 
    public static void updateAccountShippingAddress(List<Account> accountList){
        /*
            Develop an Apex Trigger so that every time 
            1. when any account is inserted then set the value of the Industry field to Education.
            Also, 
            2. check if the Description is black then set
            the value for the description to “Account Description was blank”
        */
        // sObject
        //         Standard
        //         Custom
        //List<Account> accountList = Trigger.New; // List<sObject>
        for(Account acc : accountList){ //List<sObject>
            
            if(acc.Industry == null){
                acc.Description = 'Account Industry was blank';   
            }
            
            /* 
                Develop an Apex Trigger so that every time when any account 
                is created or updated then 
                Set the Value of the Billing Address is to Shipping Address.
                ShippingStreet
                ShippingCity
                ShippingState
                ShippingPostalCode
                ShippingCountry
            */
            if(acc.ShippingStreet == null ){
                
            }else if(acc.ShippingCity == null){
                
            }else if(acc.ShippingCountry == null){
                
            }
            System.debug(acc.ShippingAddress);
            if(acc.ShippingAddress == null){
                system.debug('ShippingAddress is null ');
            }
            //  acc.ShippingStreet == null => True
            if(acc.ShippingStreet == null || acc.ShippingCity == null || acc.ShippingState == null || acc.ShippingPostalCode == null || acc.ShippingCountry == null){
                acc.ShippingStreet         = acc.BillingStreet; // data type must be same
                acc.ShippingCity         = acc.BillingCity;
                acc.ShippingState         = acc.BillingState;
                acc.ShippingPostalCode  = acc.BillingPostalCode;
                acc.ShippingCountry     = acc.BillingCountry;
            }
        }
    }
    
    
}

Dispatcher Class

public class AccountTriggerDispatcher {
    // Trigger.OperationType
    // AFTER_INSERT, BEFORE_INSERT, AFTER_UPDATE, BEFORE_UPDATE, AFTER_DELETE, BEFORE_DELETE
    // System.TriggerOperation ~= Trigger.OperationType
    // AFTER_INSERT, BEFORE_INSERT, AFTER_UPDATE, BEFORE_UPDATE, AFTER_DELETE, BEFORE_DELETE
    public static void dispatch(System.TriggerOperation operationType){
        switch on operationType{
            WHEN BEFORE_INSERT{
                AccountTriggerHandler.handleBeforeInsert(Trigger.New);
            }
            WHEN AFTER_INSERT{
                AccountTriggerHandler.handleAfterInsert(Trigger.New);
            }
            WHEN BEFORE_UPDATE{
                AccountTriggerHandler.handleBeforeUpdate(Trigger.New);
            }
            WHEN AFTER_UPDATE{
                AccountTriggerHandler.handleAfterUpdate();
            }
            WHEN BEFORE_DELETE{
                
            }
            WHEN AFTER_DELETE{
                
            }
            WHEN AFTER_UNDELETE{
                
            }
            WHEN ELSE{
                
            }
        }
    }
}

→ Apex Trigger 3

  • Create a Custom field on Opportunity “Discount” and the data type of this field should be percent.
  • Create a Custom field on Opportunity “Discounted Price” with Currency Data Type

Develop an Apex Trigger on Opportunity so that if the Discount & Amount field is not blank then calculate the discount and store it in the Discount Price field.

To Calculate the discount use the below formula and store it in a variable
Decimal discount = ( Discount * Amount ) / 100

To Calculate the Discounted Price use the below calculation and store it in a variable
Decimal discountedAmount = Amount – discount;

Questions to Ask?

  • When should the logic get executed?
    • Only Insert

Questions?

  • Which Object?
    • Opportunity
  • Which Event?
    • before insert
  • The problem that we are solving?
    • Develop an Apex Trigger on Opportunity so that if the Discount & Amount field is not blank then calculate the discount and store it in the Discount Price field.

Hands-On

trigger OpportunityTrigger on Opportunity (before insert, after update) {
OpportunityTriggerDispatcher.dispatch(Trigger.OperationType);
}

Dispatcher Class

public class OpportunityTriggerDispatcher {
    public static void dispatch(System.TriggerOperation operationType){
        switch on operationType{
            WHEN BEFORE_INSERT{
                OpportunityTriggerHandler.handleBeforeInsert(Trigger.New);
            }
        }
    }
}

Trigger Handler Class

public class OpportunityTriggerHandler {
    /*
        Develop an Apex Trigger on Opportunity so that 
        if the Discount & Amount field is not blank then calculate the discount 
        and store it in the Discount Price field.

        To Calculate the discount use the below formula and store it in a variable
        Decimal discount = ( Discount * Amount ) / 100
        
        To Calculate the Discounted Price use the below calculation and store it in a variable 
        Decimal discountedAmount = Amount - discount;
    */
    public static void handleBeforeInsert(List<Opportunity> opportunityList){
        for(Opportunity opp : opportunityList){
            if(opp.Amount != null && opp.Discount__c != null){
                Decimal discount = ( opp.Amount * opp.Discount__c ) / 100;
                Decimal discountedAmount = opp.Amount - discount;
                opp.Discounted_Price__c = discount;
                opp.Price_After_Discount__c  = discountedAmount;
            }
        }
    }
}

Watch Complete Videos

Assignment

  • Convert the Apex Trigger that you created in the previous assignment to Handler & Dispatcher Apex Classes
  • Develop an Apex Trigger on the Contact record so that when any Contact is created under any Account Record then, please
    • Populate the Contact Mailing Address with Account Shipping Address
    • Populate the Contact Other Address with the Account Billing Address
    • Make Sure you are following the Dispatcher & Handler Class concept.

Resources

Amit Singh
Amit Singh

Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion

Articles: 299

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from Panther Schools

Subscribe now to keep reading and get access to the full archive.

Continue reading