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.
In this video, we will convert all the previous apex triggers with dispatcher and handler classes along with the helper class.
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.
trigger AccountTrigger on Account (before insert, before update, after insert, after update, after delete, before delete, after undelete) {
AccountTriggerDispatcher.dispatch(Trigger.OperationType);
}
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.
trigger AccountTrigger on Account (before insert, before update, after insert, after update, after delete, before delete, after undelete) {
AccountTriggerDispatcher.dispatch(Trigger.OperationType);
}
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(){
}
}
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;
}
}
}
}
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
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?
Questions?
trigger OpportunityTrigger on Opportunity (before insert, after update) {
OpportunityTriggerDispatcher.dispatch(Trigger.OperationType);
}
public class OpportunityTriggerDispatcher {
public static void dispatch(System.TriggerOperation operationType){
switch on operationType{
WHEN BEFORE_INSERT{
OpportunityTriggerHandler.handleBeforeInsert(Trigger.New);
}
}
}
}
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