Following on from our first instalment of Apex Triggers, we’re moving on to Trigger Handlers. The way we actually calculate logic & perform actions once an action (trigger) has taken place. Although this is not a required way to work, it is best practice and recommended by Salesforce themselves.
If we follow suit and stick to the rule of 1 Trigger per object, you can imagine if we contained all of the logic & actions within the Trigger too then things would get pretty messy, pretty quickly… despite our best efforts of keeping everything organised & clean.
So this is where Trigger Handlers come into play. This is a standard Apex class that is called when the Trigger is executed and contains all of the logic & actions that otherwise would have been kept within the Trigger class.
In this example, we’ll have a Trigger on the Opportunity Object, and print a debug message whenever an Opportunity is inserted or updated
The trigger
trigger OpportunityTrigger on Opportunity( before insert, after update){
OpportunityTriggerHandler handler = new OpportunityTriggerHandler(Trigger.size);
if( Trigger.isBefore ) {
if(Trigger.isInsert) {
handler.OnBeforeInsert(trigger.New);
}
}
else if ( Trigger.isAfter ) {
if(Trigger.isUpdate) {
handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap); }
}
}
The handler
public with sharing class OpportunityTriggerHandler{
private integer BatchSize = 0;
public OpportunityTriggerHandler(integer size) {
BatchSize = size;
}
public void OnBeforeInsert(List<Opportunity> newOpportunity) {
system.debug('This fired due to a Before Insert event');
}
public void OnAfterUpdate(List<Opportunity> newOpportunity) {
system.debug('This fired due to a After Update event');
}
}