Salesforce Development Tutorial (LWC): How to use Lightning Web Component’s in List View Buttons

https://youtu.be/oPTQ-Il1eFE

Why Bother Using an LWC in a List View Button?

If you need to create some custom functionality that is accessible to your users via a list view (or potentially a related list), then a list view button is the way to go. The reason that you should prefer to utilize an LWC (despite the fact there is no obvious way to use an LWC for a list view button) is because LWC’s load faster than any other component type and, of the available list view button options, they are the most consistent with Salesforce’s Lightning Experience look and feel.

Unfortunately, while it’s super simple to setup and LWC for a list view button, Salesforce has no documentation on how to do so and virtually no answers exist for how to do this anywhere online, but NO MORE!! Today I’ll show you three different methods of creating an LWC List View button! Two methods do not allow you to send the ids of selected records in a list view and one does. I’ll give you the pros and cons of each and how to setup each one below.

One additional note, all of the below solutions will allow the user to traverse from the list view button back to the exact list view they were previously on without the help of visualforce at all! Something else that was undocumented and challenging to figure out.

DISCLAIMER: As of this writing, LWC quick actions are not usable on list views, this could change in the future however, so make sure to investigate that.


Setting up the Lightning Web Component

In any of the three scenarios we are going to use the same Lightning Web Component to demo the functionality, although in the third scenario (a flow based scenario) we will be making slight modifications to allow for the ids of records to get passed through to the component. Let’s take a look at the core of the component below (or on GitHub here).

HTML File:

<template>
	<lightning-button label="Return to List View" onclick={close}></lightning-button>
</template>

JS File:

import {LightningElement} from 'lwc';

export default class ListViewButton extends LightningElement {

	close(){
		setTimeout(
			function() {
				window.history.back();
			},
			1000
		);
	}
}

XML File:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <description>List View Button</description>
    <isExposed>true</isExposed>
    <masterLabel>List View Button</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__Tab</target>
        <target>lightning__FlowScreen</target>
    </targets>
</LightningComponentBundle>

Alright alright alright, so we have all of the files outlined above, let’s make talk about the close function in the JavaScript file first. I did an ENORMOUS amount of experimentation trying to get a list view button that spawns an LWC to allow me to traverse back to the exact list view that I had previously come from and this was the only way I could consistently get that to happen. I tried navigationmixin and it had trouble remembering where to go no matter what I did, I tried return urls, I tried a ton of junk, but that close function above does the trick every single time (at least in a browser, never tried on a mobile app). It always goes back to the exact list view I was on when I clicked the button.

So what does that function actually do? It basically looks to your browser windows history and moves back one page in time, the set timeout function allows it to take up to one second to make that happen. I would suggest using the set timeout as I had issues using this function without it, occasionally it wouldn’t have enough time to operate and failed. This however is used by thousands of users in my org now with no complaints.

The second thing I wanna go over is the XML File’s targets. For simplicity I just put every target we are going to need when we go through each of the three LWC list view button methods, that being said, you only need to declare the target for the method you choose to use. If you use the App Builder method, use the AppPage target, if you use the Tab method, use the Tab target, etc.


LWC List View Button Method 1: The Lightning App Builder Page Method

WHETHER YOU USE THIS METHOD OR NOT, READ THROUGH IT!! THE VAST MAJORITY OF THE STEPS ARE IDENTICAL FOR ALL OTHER VERSIONS SO THEY WILL ONLY BE SHOWN HERE AND REFERENCED IN THE OTHER SECTIONS!! Admittedly, this is my least favorite method, however it does work and some people may prefer it, so I’m gonna show you how to do it real quick. To use this method we need to create a lightning app builder app page. If you don’t know what that is, check out this trailhead. Once you’ve created the app builder page, you need to drag and drop the LWC (shown in the section above) onto the page. You can find the LWC in the section show below:

After you’ve placed your LWC on the page, save and activate your App Builder page. Then click anywhere in your lightning app page canvas that isn’t specifically your LWC to bring up the page information on the right side of the screen. Grab the “Developer Name” value, you need it for the next step.

Now that an app builder page houses our component, and we have the dev name for the app page, we need to setup a list view button to pop open our page for us. Kewlio Julio, let’s get to it.

Go to the object manager and find the object you are creating a list view button for. On the object page, click the “buttons links and actions” link, then click the “New Button or Link” on the top right of that page.

On the new button or link page, you are gonna fill out the follow:
1) Fill out a Label (this can be whatever you want)
2) Select the “List Button” display type
3) Select the “Display in existing window without sidebar or header” Behavior.
4) Select the “URL” Content Source
5) In the free text area put the following URL: /lightning/n/App_Page_Developer_Name
6) Save your button

To place your new LWC list view button on your objects list view, click on the “Search Layouts for Salesforce Classic” tab on your object and then click the drop down arrow next to the “List View” layout and select the “Edit” value in the drop down.

On the edit page for the list view layout, scroll down to the “Custom Buttons” section and select your new list view button.

Now, if you traverse to your object in the app launcher, you should be able to see your button on any list view and click it. This should result in your LWC popping up for you as shown below!

The Pros and Cons of this approach are the following:
Pros:
1) It’s the second fastest of the three options to load
Cons:
1) You cannot get rid of the app builder title area without janky css hacks
2) The tab method (outlined below) loads considerably faster.
3) This can load in an iframe depending on your settings.
4) Can’t pass in list view selection ids


LWC List View Button Method 2: The Lightning Component Tab Method

This is my absolute favorite method, it loads ultra fast and is the easiest to setup. If you don’t need list view ids passed into your LWC, this is the way to go in my opinion.

This method works much like the first method, the setup is virtually identical aside from the fact that you setup a Lightning Component Tab to use as opposed to a Lightning App Builder App Page. Even the List View button setup is the same, the only difference is that you use the lightning tabs developer name at the end of the URL. So to save my hands some typing I’m only gonna show you the tab setup, please refer to the rest of the steps in the App Builder setup instruction above.

To setup a tab to use instead of an app builder page is simple. In setup go to Tabs. Then on the Tabs screen, scroll down to the “Lightning Component Tabs” and select the “New” button.

On the new lightning component tab screen select your lightning component (the one shown above or the one you’ve built), enter a tab label, a tab name and select a tab style and you’re done. MAKE SURE YOUR LWC HAS A TARGET IN THE XML FOR TABS (this is shown in the code up above), otherwise it won’t be selectable.

Once you’ve created your tab, just follow the exact steps outlined in the app builder app page scenario to for the lightning button setup and you’re done!

Pros and Cons of this approach:
Pros:
1) Fastest load time
2) Easiest setup
3) Never loads in an iFrame
Cons:
1) Cannot load in list view ids from selected list view values


LWC List View Button Method 3: The Flow Screen Method

I will urge you to please not use this method unless you absolutely need the selected list view ids passed into your LWC. I say this because the load times are significantly slower and now you have to involve two technologies (flow and lwc) instead of one, making it more complex to deal with, albeit not by a ton.

The steps for setting up the actual list view button for this method are virtually identical to others as well, aside from the URL structure for the list view button, which we will cover, but refer to the first method for setting up the majority of the actual button.

Alrightyyyyy then, here we go. This final method utilizes a flow to allow us to capture the incoming selected list view ids and send them to our LWC to manipulate.

The first thing we need to do is update our LWC a bit to allow it to receive these incoming list view ids, so let’s do thattttttt. I’ll post the code below and then discuss it.

HTML:

<template>
	<p>These are the list view ids passed: {listViewIds}</p>
	<lightning-button label="Return to List View" onclick={close}></lightning-button>
</template>

JS:

import {LightningElement, api} from 'lwc';

export default class ListViewButton extends LightningElement {
	@api listViewIds;

	close(){
		setTimeout(
			function() {
				window.history.back();
			},
			1000
		);
	}
}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <description>List View Button</description>
    <isExposed>true</isExposed>
    <masterLabel>List View Button</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__Tab</target>
        <target>lightning__FlowScreen</target>
        <target>lightning__RecordAction</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__FlowScreen">
            <property name="listViewIds" type="String[]"></property>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

First let’s talk about the JavaScript file. We added two things to that file, the first is that we are now importing api at the top so that we can use the api decorator. The second is that we have created the listViewIds variable with the @api decorator on it. This allows the variable to be written to by the flow.

Next let’s talk about the metadata file, in the metadata file we have added a targetConfig. This target config allows us in the flow builder to declaratively assign the incoming list view ids to the LWC’s listViewIds variable.

Last, in the HTML file we have just created a paragraph tag to view the list view ids when they are brought over.

Now that we’ve updated the component, we need to create the flow. In setup, go to Flows and then select “New Flow” at the top to create a new flow.

You will immediately be presented with options for the type of flow you’d like to create, select “Screen Flow” and press the “Next” button., then select the “Freeform” option. You will then land on the flow builder canvas.

The first thing we need to do is create a variable. In the “Toolbox” area on the left side of the screen click the “Manager” tab and then click the “New Resource” button.

After clicking the “New Resource” button a modal will pop-up. Do the following:
1) For Resource Type select “Variable”
2) Fill out the API Name field with the value “ids” (do not include the surrounding quotes). IT MUST BE THIS VALUE TO WORK!
3) For “Data Type” select “Text”
4) Check the, “Allow Multiple Values (Collection)” checkbox
5) Check the, “Available for input” checkbox
6) Click the “Done” button


After setting up this variable you’ll need to grab a screen flow from the “Elements” tab in the toolbox and drag it onto the flow canvas.

On the Screen element modal that pops up you’ll want to do the following:
1) Enter a label and API Name
2) Uncheck the “Show Header” checkbox
3) Uncheck the “Show Footer” checkbox
4) On the left side of the modal in the “Components” area select your LWC and drop it on the page
5) Fill out the API Name for your component
6) place the “ids” variable we created above in the “listViewIds” box for the LWC
7) Click the “Done” button

Then connect your start node to your new screen node, grab the API name of your flow from the settings area of the flow canvas, activate your flow and you’re done!

The one and ONLY step that changes for the list view button setup for the flow variety is the url structure. The URL structure should be changed to the following: /flow/Flow_Developer_Name

Aside from the above, all of the other steps are the same, so please reference the first LWC Button setup method above for more info.

Pros and Cons of this method:
Pros:
1) This is the only method that can receive the ids of values selected in a list view

Cons:
1) This is by far the slowest loading method
2) It forces you to use a flow to embed your LWC
3) It’s the most complex setup
4) It hosts itself in an iFrame

Alright, that’s all folks, this blog post was long and my hands are tired. Hasta Luego!!!!!


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

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Salesforce Admin Tutorial: How to create Confetti Celebrations and use the Trailshread Audio Player

Why would we create Celebrations or use the Trailshred Audio Player at all?

To be honest idk dawg, maybe just to spice up your life a little bit and have some fun? You could make a super sweet easter egg for your Salesforce org. Maybe you wanna boost your Sales teams morale with something interesting and unexpected? No matter how you slice this banana bread chocolate chip pancake it all boils down to choosing to do something that’s a little fun for the people around you and sometimes that’s the best thing you could build. Everybody gets tired of being a serious fanci boi all day. Take a stroll down having a little fun lane for once my guy.


How to setup Confetti Celebrations using Paths

To be honest, this is super easy. If you’ve never heard of paths, you can check out some sweet info here. Basically you just do the following:

1) Go to Setup -> Path Settings and click the “New Path” button

Path Settings

2) After clicking the “New Path” button follow the steps and fill out the fields as requested, until you get to Step 3.

3) On step 3 of the Path setup there will be an area called “Enable Celebrations”. Enable them. Then pick what triggers the confetti celebrations and how often the celebrations happen.

4) Congrats, you did it!


How to use the Trailshred Audio Player to play some ultra lit audio for your Sales Broz

And now we get to the guuuuuuddddddddddddd stuff. Salesforce has created a relatively simple and lightweight unmanaged package called the Trailshred Audio Player to allow you to play audio you upload to static resources by playing an LWC on lightning record pages. Let’s check out how to use this thing.

1) Install the unmanaged package here: https://login.salesforce.com/packagingSetupUI/ipLanding.app?apvId=04t1U000007sa55QAA

2) After the Trailshred Audio Player has been installed in your org, create and upload any audio file as a static resource (the audio must be less than 5mb and be an mp3 or wav file).

3) Copy the name of the static resource you just created.


4) Go to Setup -> Custom Metadata Types -> Trailshred Settings -> Manage Records

5) Create a new Trailshred Settings record and place the name of your static resource audio file in the “Audio Static Resource Path” field, then pick the Object you want the audio to run on, pick the field you want the audio to trigger on and the value for that field it should trigger on.

6) That’s it playur, you did it! On to the next section!


Setting up the Lightning App Record Page to Play the Celebration

Alright alright alright, we’re almost there, this is the last step and it’s super easy. You gotta create a lightning record page app. Let’s check out how to get it done son.

1) Go to Setup -> Lightning App Builder and click the “New” button to create a new lightning app record page (or choose to update an existing one).

2) Search for the “Path” component on the lightning app builder page and place it on the page. This will add your confetti celebration.

3) Search for the “Trailshred Audio Player” in the component search in the lightning app builder and place it at the bottom of the page. This component is invisible (because it just plays audio) so after placing it you should just see it represented by an empty space.

4) Save and Activate your lightning app record page.

5) That’s it! You did it homie! You finally had some fun!

That’s it guys, hopefully you had a little fun building it and someone gets a good laugh out of whatever you built!

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

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Salesforce Admin Tutorial: How to Create Unique Person Account Search Layouts using formula fields

https://youtu.be/bISt9GpFzH4

Why would you want to make unique person account search layouts?

If you’re reading this, chances are you already know the answer to this, but just in case, let’s go over why you would want/need to do this.

If you didn’t know, person account search layouts are determined by the account object and that’s because person accounts are just a mash up of a contact and an account record. Every time you create a person account you are creating 1 contact record and 1 account record.

Due to the fact that the search layout is controlled by the account object, you will likely run into the following problem eventually: A group of users needs to see both person accounts and business accounts. That group of users will also get very frustrated that when searching for accounts it’s not always clear which one is a person account and which is a business account. They will also get frustrated that there are a bunch of useless fields for either the business or person accounts in their search layouts.

So how do we fix this issue?? Formula fields!! Woot!


Formula Fields to the Rescue

Thankfully, in the background, Salesforce has a field called IsPersonAccount on the Account object that is a checkbox. This checkbox allows us to know whether an account is a person account or not a person account. It also comes in great handy in search layouts and formula fields (as well as code, but we’re not gonna cover that today).

So basically what we need to do is create formula fields for our search layouts that render one field for business accounts and another field for person accounts and then put those formula fields in the search layout that the users are assigned who have access to both person and business accounts.

Let me show you an example formula for a search layout field:

IF(IsPersonAccount, PersonContact.MailingStreet, BillingStreet)

What the formula above is doing is doing is the following. If the account is a person account, show the person account mailing street. If the account is not a person account, show the billing street.

If you just follow that example above you can make the search layout fields render whatever you need them too. It’s not perfect, but it’s as close as we can get today. You then just add these formula fields to the search layout for your users and they dynamically render the correct information for the different account types.

I would also suggest adding the IsPersonAccount field to the search layout as well. It allows users to easily Id if an account is a person account or a business account.


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

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Salesforce Administration Tutorial: How to Setup Okta Single-Sign On (SSO)

Why Setup Okta at all?

This is a perfectly legitimate question, one I asked myself around 4 years ago when I setup my first Okta integration with Salesforce. The answer to this question is pretty straight forward though, let me break it down for you.

Okta Benefit #1: At the company you work for you might have 20+ different systems that users could/should be given access to and someone at your company has to manage all that access (hopefully). To simplify that problem you setup and use an access management tool like Okta. That way the person in charge of access management at your company doesn’t have to provision users by going to each individual system and provisioning them, but rather they can do all that from Okta. In short, it makes the person in charge of access management for your company’s life much easier.

Okta Benefit #2: You probably want to make sure your different apps have the same authentication policy everywhere. In other words, when a user logs in to a system they should always have the same company enforced password policies. By using Okta SSO for your systems you can make sure that the password/login policies are all the same for your org and you can easily ensure they are following policy.


Setting up your Salesforce My Domain

Before we get too far into this, if you want service provider initiated authentication to working on your Salesforce login page, you need to setup your My Domain in Salesforce. Unless something has recently changed I don’t believe this is mandatory for Identity provider initiated authentication, but chances are you’ll want to setup both authentication types.

The choice is yours, but make sure to consider this step before setting up Okta.


Creating a free Okta Developer Account

If you’re an admin reading this, don’t worry, we’re not doing any true development here, but we do need a free Okta dev account so we setup and test out our single sign-on integration with Salesforce.

You can get a free dev account here: Sign-up for a free Okta Developer Account


Setting up Okta Single Sign-On

The first this we’re gonna do after setting up our account is go into Okta and click the Applications tab. Once there click the “Add Applications” button.

After clicking the add applications button click, search for Salesforce.com in the search bar. DO NOT SELECT THE SALESFORCE FEATURED INTEGRATION!!! The featured integration does not have to ability to use SAML which we will need. There are multiple Salesforce apps in Okta. Make sure to search for and select the Salesforce.com app.

After selecting the correct Salesforce App, make sure to click the “Add” button to add the app. After adding the app you’ll need to setup its general settings. Make sure to do three things on the general settings page:

1) Select the correct instance type
2) Enter your custom my domain if you have in Salesforce in the “Custom Domain” text field.
3) Enter the correct User Profile & Type value

I typically leave the rest as is (aside from the name field, I typically change that to something more meaningful), but that’s ultimately up to you and what your okta setup needs.

After setting up your general settings, click the “Next” button in the bottom right of the page to start setting up your Sign-On Options.

In the sign in options area we want to select “SAML 2.0” as our Sign-On Method. Then we wanna click the “View Setup Instructions” button. This is super important, the “View Setup Instructions” button actually generates some values in the document it pops up that we’re gonna need when we go back to Salesforce in just a second and setup our SSO record.

Now, let’s open Salesforce in a new tab and setup our single sign-on settings and create an SSO record.

1) After opening a new tab with Salesforce go to Setup -> Single Sign-On Settings

2) Click the “Edit” button on the top of the Single Sign-On Settings page and then check the “SAML Enabled” checkbox.

3) After enabling SAML, go back to the Single Sign-On Settings page and click the “New” button for SAML Single Sign-On Settings.

4) Name the SSO record in Salesforce whatever you want.

5) Put your Salesforce My Domain url in the Entity Id field or https://saml.salesforce.com if you don’t have a My Domain setup.

6) Follow the instructions in step 6 of the Okta Setup Instructions, you opened up in Okta just a little bit ago, to fill out the rest of the SSO record in Salesforce.

7) Save your SSO record

8) After saving your record you should see an “Endpoints” section on your Salesforce SSO record and one of those endpoints should be a login URL. Copy that URL and go back to your Okta Salesforce.com App’s Sign-On Options page.

9) Once you’re back to your Salesforce.com app in okta, place the Login URL you copied from Salesforce into the Login URL in your Okta Salesforce.com App.

10) Click the “Done” button at the bottom of the page in Okta.

11) That’s it your SSO setup is done! Now we just need to important our users into Okta from Salesforce.


How to setup our Salesforce integration to import our Users from Salesforce into Okta

The final thing we need to do is import our users from Salesforce into Okta so that we can assign them the Salesforce app in Okta and give them access to Okta in general.

To this we need to do a few things:

1) In the Salesforce.com App we just setup in Okta we need to click the provisioning tab.

2) We then need to click the “Configure API Integration” button

3) After clicking that button we need to check the “Enable API Integration” checkbox that pops up and then enter our username and password + security token.

4) Click the “Test API Credentials” button to make sure you are connecting successfully to Salesforce.

5) Click the “Save” button after you connect successfully


How to Import our Users from Salesforce to Okta

Now that we have our integration setup, importing users is pretty simple we just need to follow a few steps:

1) In your Salesforce.com app in Okta click the Import tab.

2) Click the “Import Now” button on the import tab. This will scan your Salesforce org for users who aren’t yet assigned to the Salesforce.com app in Okta.

3) After the users are scanned in Salesforce, Okta will display a list of users who are not currently assigned to your Salesforce app in Okta. Check the boxes next to each user you intend to import into Okta and assign to the Salesforce app

4) After checking the boxes next to the users, click the “Confirm Assignments” button to confirm the users should be brought into Okta and assigned to the Salesforce.com app.

5) You did it! All done!


Demoing your Single Sign-On from Okta to Salesforce

If you set everything up right and you linked your Okta user with your Salesforce user, you should be able to click the “My Apps” button at the top of the screen and see your Salesforce.com app as a button you can click once you are at your My Apps screen. Clicking that Salesforce.com button should automatically sign you in to Salesforce! Woot!!


How to setup Service Provider Initiated Authentication in Salesforce

This part is super easy as long as you followed along above and created a my domain. We just need to do the following:

1) In Salesforce go to Setup -> My Domain

2) In the “Authentication Configuration” section of My Domain, click the edit button

3) Check the box next to the “Authentication Service” that represents the SSO record you setup for Okta just a little while ago.

4) Click the “Save” button

5) All done! You can test this out by logging out of Salesforce and using the new Okta button you see on your login page!


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

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

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