Salesforce Development: How to use Custom Settings to Bypass Your Triggers in Production

Why On Earth Would We Ever Build Trigger Bypasses?

This is an excellent question and one I wondered myself… until my team and I had to do a monstrous 50,000,000 record load into Salesforce for a deployment, lol. I was stumped… how on earth could I ever pull this off without taking days or weeks to upload that data. We’re not gonna into all the detail behind that monster data load, but we’ll just say turning off the triggers was a part of it. Then we were faced with the, you can’t turn off the system while we do this data load and I was like, fml, how though? As it turns out there is a way! And a really good and simple way if you leverage Custom Settings.

There are a number of other reasons to do this too. A data team that loads data that’s pre-transformed (doesn’t need to go through the trigger) or an integration that auto-transform the data and doesn’t need to be bogged down by a trigger. There are plenty more beyond these as well, but these are the major ones.

What are Custom Settings?

Custom Settings are much like Custom Metadata in that they are typically used in the same way as a config file in another programming language. That being said they are a bit different. Unlike custom metadata, custom settings allow you to change the values of the data you store based on the user that is currently running the code. So each user in your system can have different values for custom metadata records. Pretty nifty, if I do say so myself.

So How Do We Set This Bypass Up?

This is so simple it’s mind boggling, lol. All you need to do is setup a hierarchy custom setting object by going to Setup -> Custom Settings and then create Checkbox (Boolean) fields for each object you have a trigger for that you may want to bypass.

After you’re done setting that bad boi up. Click the “Manage” button at the top of your custom setting so that you can create records for it. After you do that you’re going to be presented with two different “New” buttons on the screen and it’s not super obvious what either of them do, so let me explain. The top “New” button is to make default values for ALL USERS in your org. This is the Default Organization Level Value. The bottom “New” button allows you to make new records that are only relevant to certain Users or Profiles. The bottom “New” button is what we want to click.

After clicking the bottom “New” button you’ll be presented with option to select a, “Location” which is the most confusing label of all time, lol. This just expects you to choose a User or a Profile which will then allow you to have unique values for Users and Profiles for your custom setting! Pretty Kewllllllll. Select the profile or user you would like to bypass your trigger(s) and select the checkboxes for the triggers they should bypass and then hit “Save”.

That’s it, pretty damn simple. Now on to the equally simple trigger code.


The Trigger Code

You might be thinking, oh no code… I’m sorry if you feel that way because code is the most amazing thing since General Tso’s Chicken. However, if you do, no worries, we need four lines of code… yes that’s it. Now before I show you this code, please note, you should be utilizing a trigger framework for your code and that no logic should live in your triggers… but that’s for another day. This is just a simple example, so lets check it out.

trigger Account_Trigger on Account (before insert)
{
        //Getting the Process_Switches__c custom setting value that is relevant to our running 
        //user
	Process_Switches__c processSwitches 
        Process_Switches__c.getInstance(UserInfo.getProfileId());

        //If the user can bypass the trigger, return and do not continue the trigger.
	if(processSwitches.Account_Process_Bypass__c)
	{
	    return;
	}

        //Call your trigger handler and run trigger logic
}   

Woop, there it is. Pretty simple stuff. If you’re not familiar with Custom Settings and the unique ways to query data from them the whole [Custom Setting Name].getInstance(UserInfo.getProfileId()) might look a little confusing. It’s pretty simple though. It basically gets the custom setting record that is relevant for the running users profile. This makes sure we always get the correct record and only the right people are bypassing the trigger! Pretty kewl huh? And that’s it, yep, that’s really it. Now go enjoy a trigger free world where your data loads go lightning fast.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Salesforce Development: How to Make Sure Your Process Builders Never Fire Your Apex Triggers

Why Would We Want Our Process Builders to Bypass Our Triggers?

If you didn’t know process builders fire your triggers every single time they make an update to a record or insert a new record. If you have 5 different update actions in your process builders that means you could potentially fire your triggers 5 times in the same process builder execution!! That would absolutely destroy your operation speeds, and if you didn’t know Process Builders are already know to be very poor performance wise (taking up to 40 times longer than flows or triggers to operate). That being said even process builders have their place, especially in admin heavy orgs. So let’s figure out how to make sure they are as performant as they can be.

As a side note: If your process builders rely on your trigger to re-run after they execute… you have a problem and you need to fix it. Process builders should never require a trigger to re-run after it executes.

SUPER IMPORTANT NOTE: Make sure to re-start your triggers at the end of your process builder. If you don’t you could have pretty horrible ramifications with the data loader and with Database all or none transactions. Don’t worry we go over how to restart them in your process builder as well.


Setting Up The Super Simple Apex Code To Make This Work

First things first. If you want the code and config for this , you can grab it here on github.

Now let’s get to it! Unfortunately we have to write a little apex code to make this magic work (or fortunately if you love code like me), but don’t worry! It’s very simple. The first this we’re going to make it a small utility class that allows us to pass in the name of a trigger we’d like to bypass.

//The utility class that allows us to determine which triggers we want to bypass
public with sharing class Util_Trigger_Name_Bypass
{
	//The set of trigger names that we want to bypass in our trigger.
        public static Set<String> bypassedTriggers = new Set<String>();

        //Method that allows us to add a trigger that we want to bypass
	public static void bypassTrigger(String triggerName)
	{
		bypassedTriggers.add(triggerName);
	}

        //Method that allows us to remove a trigger from our bypassed triggers set
	public static void removeBypass(String triggerName)
	{
		bypassedTriggers.remove(triggerName);
	}
}

There is one major thing to note about the code above. We utilize the static keyword to declare our variable (and our methods too). If you are not familiar with the concept of static (or class) variables, you should definitely take the time to investigate them more, but I will briefly explain it here. Static variable persistent for your entire execution context. What this means is that our variable’s value will remain the same in the trigger and the process builder (and anything else after or inbetween). This is critical! If it wasn’t a static variable we wouldn’t be able to achieve this.

Now that we have this nice utility class that allows us to put the names of the triggers we would like to bypass. Let’s write a couple more small apex classes with invocable methods that our process builder can call to add the name(s) of our triggers we would like to bypass while our process builder is running.

//Class that you can call from a process builder that allows you to stop a trigger from executing
public with sharing class Util_PB_Trigger_Stop
{
	//You can find this invocable apex method in your process builder when you look for 
        //the "StopTrigger" label in an apex action.
	//This method adds trigger names to the utility we made that stores trigger names we 
        //would like to bypass.
	@InvocableMethod(Label = 'StopTrigger' Description='Method allows up to bypass 
        triggers')
	public static void stopTriggers(List<String> triggerNames)
	{
            Util_Trigger_Name_Bypass.bypassTrigger(triggerNames[0]);
	}
}
//Class that you can call from a process builder that allows you to start a trigger again
public with sharing class Util_PB_Trigger_Start
{
	//You can find this invocable apex method in your process builder when you look for 
        //the "StartTrigger" label in an apex action.
	//This method removes trigger names from the utility we made that stores trigger names 
        //we would like to bypass.
	@InvocableMethod(Label = 'StartTrigger' Description='Method allows up to restart 
        triggers')
	public static void startTriggers(List<String> triggerNames)
	{
		Util_Trigger_Name_Bypass.removeBypass(triggerNames[0]);
	}
}

As you can see the above apex classes just allow us to add or remove the names of our triggers we want to bypass to our utility class’s bypassedTriggers Set. Noice, very convenient and very simple. The last two things we need to do are update our trigger, so that it looks to our Util_Trigger_Name_Bypass utility class to determine if it should run and create our process builder!. Let’s take a look at the trigger.

//Our Case Trigger. Please use a trigger framework and never put logic in your triggers.
//I created this trigger in this way for demonstration purposes only and to
//simplify this lesson.
trigger Case_Trigger on Case (before update, before insert)
{
	//Looking at our utility class to determine if we should run our trigger logic.
        if(!Util_Trigger_Name_Bypass.bypassedTriggers.contains('Case_Trigger'))
	{
		Case_Trigger_Handler.beforeUpdate(trigger.new);
		Case_Trigger_Handler.beforeInsert(trigger.new);
	}
}

As you can see from the above trigger, before we execute the logic for our trigger we first check to determine whether or not our utility class’s bypassedTriggers set contains the name of our case trigger. If it does, then we do not execute our logic.


Setting Up The Process Builder

You can setup your process builder to bypass your triggers in two different ways. You can have your process builder shut off the trigger before it runs any operations or you can have it shut off the trigger just within the immediate action blocks that actually update or insert records. I would personally suggest you just turn it off for the entire length of the process builder because it’s more performant that way, so that’s what I’m going to show you below. If you would rather do it the other way, the video linked above explains it in detail.

As you can see from the above pictures this is super simple! We just create two nodes, one to stop the trigger at the beginning of the process builder and one to re-start the trigger at the end of the process builder. Both of those nodes have apex actions within their immediate actions that call the StopTrigger and StartTrigger Invocable apex methods respectively and pass it the name of our trigger we want to disable (in our case the Case_Trigger). Then you place any update or insert actions between those two nodes and you’re good to go! No more trigger logic run while your process builders execute! Wooottttttttt!!!!!!!!! Enjoy that massive boost in process time. The only next steps you have are to eliminate your process builders entirely, lol, because they are just garbage.

SUPER IMPORTANT NOTE: Make sure to re-start your triggers at the end of your process builder. If you don’t you could have pretty horrible ramifications with the data loader and with Database all or none transactions.

Moderately Important Note: Make sure you “Evaluate Next Criteria” in the “Specify What Happens After Evaluating This Criteria” node.


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps