Salesforce Apex Trigger Framework, Best Practices

Lets discuss about general trigger first then we will implement that with trigger framework.

The requirement is to create a trigger on Salesforce that will automatically create the Account record in the system when a new Contact record is created.

With this trigger code, the Account getting created will use the Contact’s firstname and lastname as Acconut Name, though you could easily customize this to what works for you.

Here’s the code, complete with a unit test so that you can deploy

Here is the test class for above trigger –

Trigger Framework

A trigger handler framework is a way to remove logic from your triggers and enforce consistency across the platform. The framework itself will do the heavy lifting for you in terms of figuring out which kind of trigger is currently running and firing the correct logic.

Trigger Interface:

The interface dictates which methods every trigger handler must implement, even if these methods have no code in them.

TriggerDispatcher

The dispatcher is responsible for making sure all of the applicable methods on your trigger handler are called, depending on the current trigger context. It also contains a check to make sure that the trigger has not been disabled.

Custom Setting
Create the custom setting, see screenshot below –

Customsettingstrigger

Then insert one record into custom setting –

triggersettingdata

ContactTriggerHandler

We need to implement the ITrigger interface. We need to add “Implements ITrigger” to the end of the class declaration, and then we need to add all of the methods from the interface to the class, even if those methods do not contain any logic.

Trigger 

Create a trigger on your object and make sure it fires on all events. We only need a single line of code to hook the trigger handler in via the dispatcher.

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

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