Trigger Handler Pattern in Salesforce Apex : Bijay Kumar
by: Bijay Kumar
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of the Content When writing Apex triggers in Salesforce, developers often include all the logic within the trigger class itself. However, this can lead to complex and hard-to-manage code, especially when multiple processes need to be automated for the same object. To address this, Salesforce recommends using a **trigger handler** and **helper class** pattern. **Key Concepts:** 1. **Trigger Handler Pattern**: This design pattern helps organize the logic executed within Apex triggers, making the code cleaner and easier to manage. 2. **Trigger Helper Class**: This is an Apex class that contains methods for handling various trigger events (like before insert and after update). It allows developers to define the order of method execution clearly. 3. **Best Practices**: It’s best to have one trigger per object to control the execution order effectively. **Examples Provided**: - **Updating Related Contacts**: An example shows how to automatically update the level of related contacts when an account's subscription type changes to 'Platinum'. - **Sending Emails**: Another example demonstrates how to send an email to the account holder upon the creation of a new account. ### Additional Context Using the trigger handler pattern not only simplifies the code but also enhances its reusability and maintainability. This is crucial in environments where multiple developers may work on the same codebase, as it promotes clarity and reduces the risk of errors. ### Hashtags for SEO #Salesforce #ApexTriggers #TriggerHandler #SalesforceDevelopment #ApexProgramming #SalesforceBestPractices #CodeOrganization #SalesforceApex #SoftwareDevelopment #SalesforceTutorials
Usually, when we write the Apex Triggers, we write the trigger class and also implement the logic in the same class. Let’s say you created a trigger to automate the process of updating fields on the Account object when a specific condition is met.
Now, again, you need to automate any other processes on the same object, and if you keep adding more things, it will become difficult for you and other developers to understand the code.
To keep the code clean, more organized, and reusable, we have the trigger handler and helper class in Salesforce Apex.
In this tutorial, we will learn about the trigger handler pattern in Salesforce Apex, its purpose, and how to create an Apex trigger handler and helper class using examples and step-by-step explanations.
What is the Trigger Helper Pattern in Salesforce Apex?
The trigger helper pattern in Salesforce is a design used to organize and manage the logic executed within Apex triggers.
A trigger helper means keeping the logic of the trigger in the same class. This helps keep the trigger short and clean.
It’s very useful when we have many actions, such as before insert, after update, or when our trigger has a lot of logic. It makes your code easier to manage, understand, and update in the future.
What is the Apex Trigger Handler Class in Salesforce?
A trigger handler class is an Apex class that contains methods to handle various operations for triggers. This class includes methods for various trigger events, such as ‘before insert’ and ‘after update’, and processes the logic relevant to each event.
We should always use a helper class (apex class) with a trigger class. It makes the code’s functionality easy to understand.
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, we don’t know which method will execute first because there is no defined order for implementing the methods.
To avoid this, we create the helper class, which is a regular Apex class. In that class, we develop all the methods and implement the logic that we want to execute.
After creating the helper class, we need to create the trigger, and within the trigger, we can call the methods in the desired order to execute.
Implement the Trigger Handler Pattern in Salesforce Apex
One trigger per object is the best practice for implementing triggers in Salesforce Apex. 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 context.
Syntax: Apex Trigger Helper Class in Salesforce
The helper class is a simple Apex class that defines various methods and implements the necessary logic to fulfill our functionality.
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 );
}
Apex Trigger Helper Class in Salesforce
First, I will explain how to create an Apex trigger helper class in Salesforce and where the actual logic of the trigger is implemented. It is designed to handle multiple trigger events and sObjects.
Example 1: Update Fields Automatically Using Salesforce Apex
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 regular Apex class and then implement the methods using the desired logic to automate the process.
Here, I added a method ‘updateRelatedContacts’ with an account list collection to update the related contacts, and then declared 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 then created a list of contacts that returns only the related contacts of the 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;
}
}
}
Example 2: Send Email Automatically Using Salesforce Apex
For example, we want to send an email to the account holder when a new account is created. To achieve this, we need to create a trigger helper class and invoke its methods within the trigger handler class.
In the Apex trigger helper class below, I created a class to automate the process of sending an email to the customer when a new Account record is created.
Then, an email should be sent to the account holder to notify them that your account has been successfully created.
First, I created an Apex helper class named SendEmailTrigger and the sendEmail() method, through which we passed the List Collection of accounts named newAccounts.
Then, in the for each loop, I created an account instance named ‘acc’ and assigned ‘newAccounts’ to it. Whenever a new account is created, it will be added to the acc instance.
Then, using the if condition, we checked whether the email field is not blank, because as we wanted to send an email to the account holder for that, the email field should not be null.
Then, I created a Massaging class instance named email. Now, using this instance, we will create the content of an email, and for that, we need to use the methods that I explained above. Then, using the email instance, we declared methods to add content to the email.
Methods we used in the Apex class:
- setToAddresses(): We provided the account holder’s email address as the recipient’s email.
- setSubject(): Assigned subject to the mail.
- setPlainTextBody(): Created email body in plain text without using any HTML text.
Then, we checked whether the list we created was not empty and then added it to the Messaging.sendEmail() method to send an email.
public class SendEmailTrigger {
public static void sendEmail (List<Account> newAccounts) {
List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();
for (Account acc : newAccounts) {
if (String.isNotBlank(acc.Email__c)) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { acc.Email__c });
email.setSubject('New Account Created: ' + acc.Name);
email.setPlainTextBody('A new account has been created with the name: ' + acc.Name);
emailsToSend.add(email);
}
}
if (!emailsToSend.isEmpty()) {
Messaging.sendEmail(emailsToSend, false);
}
}
}
Create Apex Trigger Handler Class in Salesforce
The trigger handler is the trigger class where we can call different methods to execute the logic that we implemented in the helper class.
First, we need to create an Apex Trigger on the Account object and add the relevant events to the trigger to determine when it should execute.
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.
After that, we have also created another helper class to send an email when a new account is created. That class also needs to be called here. As the email should go after account creation so here we used Trigger.isAfter && Trigger.isInsert context variables.
trigger CallAccHelperClass on Account (after insert) {
if ( Trigger.isAfter && Trigger.isUpdate ) {
AccHelperClass.updateRelatedContacts ( Trigger.new );
}
if ( Trigger.isAfter && Trigger.isInsert ) {
SendEmailTrigger.sendEmail ( Trigger.new );
}
}
Proof of Concept
Before updating the subscription type field on the account object, you can see that the related contact’s level is set to secondary.
I will update the subscription type to platinum, and let’s see whether the contact level field can be set to primary automatically.

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

Now, as I create the new account record, the email will be sent to the email address that we provided in the email field.

Here you can see the account holder received the email with content that we added in the Apex class.

Conclusion
I hope you now have an idea about the trigger handler pattern in Salesforce Apex. In that, I explained the Apex handler 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:
- Apex Triggers in Salesforce
- Logical and Looping Statements in Salesforce Apex Programming
- Polymorphism in Salesforce Apex
- Inheritance in Salesforce Apex
The post Trigger Handler Pattern in Salesforce Apex appeared first on SalesForce FAQs.
April 30, 2025 at 06:49PM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment