Apex Trigger Handler and Helper Class in Salesforce

As a Salesforce developer, I want to automatically update all related contact records when an opportunity is marked as Closed Won. Usually, we write the logic in the trigger class itself, but instead of writing the logic directly in the trigger, I use a helper class to handle the bulk of the processing.

Here, I will explain what the apex trigger helper class in Salesforce is, why we need it, and how to create the apex trigger handler and helper class in Salesforce using examples and step-by-step explanations.

What is Apex Trigger Handler Pattern in Salesforce?

The trigger handler pattern in Salesforce is a design pattern used to organize and manage the logic executed within Apex triggers. The handler pattern is to separate the trigger logic into a separate class from the trigger itself.

It builds on the idea of a trigger helper class. Still, it is an additional structure, mainly when dealing with multiple events (before insert, after update, etc.) or when a trigger becomes complex.

What is Apex Trigger Helper Class in Salesforce?

A trigger helper class is an Apex class that contains methods to handle various operations for triggers. This class includes methods for different trigger events (like before insert and after update) and processes the logic relevant to each event.

According to “Best Practices” suggested by Salesforce, we should always use a helper class (apex class) with a trigger. It makes it easy to maintain the code in the long term.

Why do we need to use a trigger helper class in Salesforce Apex?

When we create a trigger and write the different methods, events, and logic in the trigger class itself, when we execute the trigger or automate any process, we don’t know which method will execute first because there is no order for executing the methods.

To avoid this, we create the helper class, which is a simple Apex class. In that class, we create all methods and implement the logic that we want to execute. After creating the helper class, we need to create the trigger, and in the trigger, we can call the methods in the order we want to execute.ccc

Implement Apex Trigger Handler Pattern in Salesforce

A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts.

Syntax: Apex Trigger Helper Class in Salesforce

So, the helper class is a simple Apex class where we create different methods and implement logic for what we want to do.

public class AccountTriggerHelper {
    
    public static void FirstMethod(List<Account> newAccounts) {
        // Enter Logic;
    }

    public static void SecondMethod(List<Account> updatedAccounts, Map<Id, Account> oldAccountMap) {
        // Enter Logic;
    }
}

Syntax: Apex Trigger in Salesforce

Now, in the Apex trigger, we need to call the methods that we created in the helper class, and you can call the method in the execution order you require.

trigger AccountTrigger on Account ( before insert, after update ) {

       AccountTriggerHelper.SecondMethod ( Trigger.new );
       AccountTriggerHelper.FirstMethod( Trigger.new, Trigger.oldMap );
}

Create Apex Trigger Helper Class in Salesforce

So first, I will explain how to create an apex trigger helper class in Salesforce, and in this handler class, where the actual logic of the trigger is implemented. It is designed to handle multiple trigger events and sObjects.

For example, we need to automate the process of automatically updating all account-related contacts’ level_c field values to ‘Primary‘ when the account subscription_type_c is updated to ‘Platinum‘ using the Apex trigger.

Here, you need to create a simple Apex class and then implement the methods using the logic you want to automate.

So, I added a method with an account list to update the related contacts and then initiated the contact list. Then, in the for each loop created an instance of the account object and assigned a newAccounts variable, which is a list of records that the user will update in the account object.

In the if condition, we checked whether the subscription type is equal to platinum and again created a list of contacts that returns only related contacts of any current account, which you will update.

Again, created a for loop that iterates over related accounts and changed the level field value to primary in the contact object. Add the record to the list and update the list outside the for loop.

public class AccHelperClass {
    
    public static void updateRelatedContacts (List<Account> newAccounts) {
        List<Contact> contactsToUpdate = new List<Contact>();
        
        for (Account acc : newAccounts) {
            if ( acc.Subscription_Type__c == 'Platinum' ) {
                List<Contact> relatedContacts = [ SELECT Id, Level__c FROM Contact WHERE AccountId = :acc.Id ];
                
                for ( Contact contact : relatedContacts ) {
                    contact.Level__c = 'Primary';
                    contactsToUpdate.add(contact);
                }
            }
        }
            if ( !contactsToUpdate.isEmpty() ) {
            update contactsToUpdate;
        }
    }
}

Create Apex Trigger in Salesforce

The apex trigger is essentially the point where we can invoke different methods to execute the logic implemented in the helper class. First, we need to create an Apex Trigger on the account object to enter the event.

Here, I added an if condition to check whether, using the context variable, we are calling events, which are isAfter and isUpdate. Then, using the helper class name, call the methods in the order you want to execute.

trigger CallAccHelperClass on Account (after update) {
    
    if ( Trigger.isAfter && Trigger.isUpdate ) {
        AccHelperClass.updateRelatedContacts ( Trigger.new );
    }
}

Proof of Concept

So, before updating the subscription type field from the account object, the related contact’s level is secondary. I will update the subscription type to platinum, and let’s see whether the contact level field can be set to primary automatically.

Apex Trigger Handler and Helper Class in Salesforce

As I update the subscription type to platinum from the account object, the level field of the contact object will automatically change to primary.

Trigger Handler Pattern in Salesforce Apex

Conclusion

I hope you now have an idea about the Apex trigger helper class in Salesforce. In that, I explained the Apex handler pattern and the trigger helper class. Then, we have seen the syntax for declaring a trigger and the trigger helper class.

After that, using an example, I explained how to create an apex trigger helper class and call the helper class in a Salesforce trigger.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.