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 Tutorial (LWC): How to create Custom Lightning Web Component Utility Modules

Why create Utility Modules for Lightning Web Components?

If you’re asking this question, I have feeling you don’t often utilize utility modules (or utility classes) anywhere… so let me be the first to welcome you to this absolutely magical world of utilities. They will make your life easier, code updates simpler and your code base a lot less terrifying.

Utility modules are useful in LWC’s because they allow you to take code you commonly use (or may commonly use) between components and allow tons of different components to use that same code without re-writing it a bunch.

Here’s a simple example. Say you pull URL parameters in several different lightning web components and in all of those components you have the exact same method that parses the url and returns those parameters. Instead of adding that method to every single component and having to update that method any time your process for parsing URL parameters change, you could just make a javascript utility module to deal with it, import it into your components and just call that single javascript utility module everywhere you needed to parse URL parameters. In the end this greatly reduces your codebase and the difficulty updating your code in the future.

Maybe the above is still confusing, no worries, let’s check out an example that will hopefully clear any confusion up.


How to create a Utility Module

So to give you a little background on what we’re about to do, I would suggest a little light reading on ES6 Javascript Modules. This will give you a bit better understanding on how all this code I’m about to show you works. If you’re not as obsessive of a reader as me, don’t worry though, I’ll explain everything just a bit throughout the rest of this post.

The first thing we need to do is create an LWC and delete the html file that comes with it as well as all the pre-built code in the javascript file. You might be like wutttttttt??????? But no worries, with utility modules you won’t need them. I know it feels weird right now, but just trust ya boi for one sec.

Next let’s take a look at a very simple LWC module with some exports in it. The name of the below LWC is “util_module”. Knowing the below components name will be important in the near future (GitHub where this code is also available).

//DISCLAIMER: There are many different ways available in ES6 JS to export variables, functions and classes
//you can find out more about exports here: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

//How to export a variable and make it available when importing your module
//in other components
export const OPEN_STATUS = 'Open';

//How to export a method and make it available when importing your module
//in other components
export function showError(error) {
    return 'This is an error ' + error;
}

//How to export a class and make it available when importing your module
//in other components
export class util_class {

    newStatus = 'New';

    showConsoleLog(){
        console.log('This is the console log ::: ');
    }

}

So what is all that junk up there? It’s not all that complicated after you get familiar with it. Basically what you are seeing are a handful of ways to make things accessible in a javascript module. The key thing here is that “export” keyword. Placing the export keyword in front of a variable, function or a class will allow you to import them into other components. Which brings us to the next part of this lesson, “How tf do we use this utility module”. Let’s check that out.


How to Import/Use your LWC Utility Module

Alright my guys (and gals), let’s check out the code to import that adorable little utility class we made up there into one of our normal LWC’s .

import { LightningElement } from 'lwc';

//Importing in our javascript utility module. The import variable names (OPEN_STATUS, //showError, util_class)
//are the names of the exported variable, method and class in our util_module component
import { OPEN_STATUS, showError, util_class} from 'c/util_module';

export default class Demo_component extends LightningElement 
{
    openStatus;
    returnedError;
    newStatus;

    //The connectedCallback method runs on component load
    connectedCallback()
    {
        //assigning our imported OPEN_STATUS value to our local openStatus variable
        this.openStatus = OPEN_STATUS;

        //assigning our imported showError methods return value to our local returnedError 
        //variable 
        this.returnedError = showError('Tacos had an error');

        //assigning our imported class's newStatus variable to our local newStatus variable
        this.newStatus = new util_class().newStatus;

        //Calling our imported class's showConsoleLog method
        new util_class().showConsoleLog();
    }
}

You’re thinking one of two things right now. It’s either, “Whoa my guy, it’s really that easy?” or, “Idk wtf that mess means”. For the group in latter, let me help you get into the former group with a little bit of an explanation.

Near the top of our LWC you’ll notice this line:

import { OPEN_STATUS, showError, util_class} from 'c/util_module';

This statement is importing the this various things we marked with the “export” keyword in the util_module LWC we created above. You will notice that the OPEN_STATUS, showError and util_class all are the exact names of the things with the “export” statement next to them in the util_module LWC.

These OPEN_STATUS, showError and util_class imports now become accessible in your class via those keywords. So for instance when we do this assignment:

this.openStatus = OPEN_STATUS;

We are literally assigning the OPEN_STATUS variable value from our util_module LWC to our local openStatus variable. Pretty cool right? Hopefully this makes things a little clearer… maybe… If I’m lucky anyway.

And that’s really it everyone! If you have any questions feel free to ask. I typically respond pretty quick.


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 Tutorial: How to Implement a Trigger Framework

Why use a Trigger Framework?

There are a couple big reasons why you would want to implement a trigger handler. Let’s check them out below:

1) It makes your triggers way easier to test. By putting your logic in your trigger handler, instead of your trigger you allow yourself a much simpler path to testing your trigger. You don’t have to do tons of real inserts on the object to test the logic within the trigger, you could create mock objects and call the trigger handler class to test the logic in your trigger instead (test mocking is a wonderful thing that saves you tons of time, but we’re not covering that today).

2) It allows your trigger code to be leveraged in other places. Maybe your trigger handler code could be used in a lightning web component, aura component, a batch class, etc. By creating this code in a trigger handler (or by having that handler call a utility class), you have the option for other code to utilize it as well, reducing the overall code in your org.

Which Trigger Framework should I use?

There are tons of great trigger frameworks, but my personal favorite is the sfdc-trigger-framework. I prefer it because it’s super lightweight, you get the benefits I mentioned above, it’s easy to extend upon it if you need to and it’s not super complicated to learn.

This allows you to get your teams on board and using the framework super quick and the ease of extensibility allows you add whatever extra functionality you need without it getting super confusing and difficult.

How to use the Framework?

After you’ve download the TriggerHandler class from the sfdc-trigger-framework repo and put it in your org, it’s actually pretty simple, but let’s just take a look. We’ll build the trigger handler class for the case object first:

public with sharing class Case_Trigger_Handler extends TriggerHandler 
{
    public override void beforeInsert()
    {
        //Logic/method calls here
    }    
}

So what’s goin on above? Basically what we’ve done is created an apex class that extends the TriggerHandler class so that it can benefit from all the accessible methods within it through the concept of inheritance. We’re able to override the beforeInsert virtual method in the TriggerHandler class to give it logic that is unique to the case trigger. Pretty kewl huh?

Now let’s check out the actual Case Trigger.

trigger Case_Trigger on Case (before insert) 
{
    new Case_Trigger_Handler().run();
}

Wow… there is almost nothing there… wyld. Basically what we’re doing is creating an instance of the Case_Trigger_Handler class and calling the run method that it inherited from the TriggerHandler class it extends. We can check out that method below:

// main method that will be called during execution
    public void run() {
  
      if(!validateRun()) {
        return;
      }
  
      addToLoopCount();
  
      // dispatch to the correct handler method
      switch on this.context {
        when BEFORE_INSERT {
          this.beforeInsert();
        }
        when BEFORE_UPDATE {
          this.beforeUpdate();
        }
        when BEFORE_DELETE {
          this.beforeDelete();
        }
        when AFTER_INSERT {
          this.afterInsert();
        }
        when AFTER_UPDATE {
          this.afterUpdate();
        }
        when AFTER_DELETE {
          this.afterDelete();
        }
        when AFTER_UNDELETE {
          this.afterUndelete();
        }
      }
    }

If you checkout the TriggerHandler class you’ll see that method within it. Basically what it’s doing is checking whether or not the trigger should run, and then running the method for the respective trigger context we’re currently in. Pretty simple, pretty kewl. That’s literally all it takes to leverage this framework for your own code.

More info on the trigger framework

There is a lot more stuff you can do with this framework and you can check out more of it in the video linked above or in the github repo. One of the best features is being able to dynamically turn your triggers on and off super easily from the code! So make sure to check that out!


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 Tutorial: How to use the SFDX Scanner Salesforce CLI Plugin for Static Code Analysis

Why Use Static Code Analysis Tools?

There are two major reasons to use static code analysis tools:

1) They make you a better developer. These industry standard rules exist for a reason. To make code clean, modular and easy for all the developers that come after you to deal with. So be a kewl guy and make some beautiful code.

2) If you haven’t had to deal with this, I envy you, but for many of us out there you will eventually have your codebases reviewed by a third party. It may even be Salesforce themselves, and when they review your codebase they will run these tools against it to gauge the health of the code in your org. I have seen people lose contracts because of this (and in some cases rightfully so), but if you are constantly running a static code analysis tool again your code you write every sprint and fixing the problems it finds, you’re not gonna see too many issues pop-up when someone else reviews the code.


How to use the SFDX Scanner Plugin?

To utilize the SFDX Scanner plugin we need to do the following (Checkout the GitHub wiki I wrote here):

1) Install the Java Development Kit (JDK) version 8 or higher

2) Install the Salesforce CLI

3) Setup a Salesforce VS Code Project

4) Install the sfdx scanner plugin for the Salesforce CLI by opening up a terminal window and running the following command:

sfdx plugins:install @salesforce/sfdx-scanner

5) Open the Terminal in VSCode and run the following command to scan your entire codebase for all static code issues (make sure to replace pathToFile.csv with the actual path for your file):

sfdx scanner:run --target "**/default/**" --format "csv" --outfile "pathToFile.csv" 

6) The above command will output a csv that shows you all of the issues with the code in your org within a few seconds (unless you have a mega code-base. It may take a few minutes then).

7) For more information on the wealth of configuration options you have with this cli plugin, please check out the SFDX Scanner GitHub repo

That’s it guys! Pretty simple! There are a ton of additional configuration options you can do with this CLI plugin and you can check them out in the GitHub repo linked above. In a future article I will hopefully show you how to make custom pmd rules and rulesets to use if you aren’t a fan of the default ones, but that’s a pretty big topic.


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 Tutorial: How to Setup Uncrustify to automatically format your code in Visual Studio Code

Why would you want to setup Auto Code Formatting?

Aside from the fact that it’s both magical and amazing, it also enables you to easily do a couple things:

1) If you get onboarded to a project with a horrific looking codebase with nightmarish formatting, you can fix that by running a single command on the entire thing to fix it. This saves you what would otherwise take dozens if not hundreds of hours of time

2) If you are on a large team of developers and you want your code to all look the same (at least on your commit to your codebase), you can create one code style configuration file and distribute it to the entire team for use. This way your code all looks and reads the same which makes everything just a little bit nicer to deal with.

There are other reasons but those are the two major ones I can come up with off the top of my head here, lol.


Why use Uncrustify for auto-code formatting?

I like Uncrustify for automatic code formatting because it has so many configuration options, 735 in fact! It allows you to configure how you like your code to look as opposed to many other popular auto-code formatting tools that are “opinionated” that don’t give you that flexibility.


How to Setup Uncrustify

To utilize Uncrustify with your Salesforce projects in Visual Studio Code you need to do the following (Github wiki is here):

1) Install Uncrustify locally on your machine. I would suggest installing it via a package manager like chocolatey or npm if you are using a windows machine (you may need to download npm or chocolatey if you haven’t already)

2) Install the Uncrustify Visual Studio Code plugin. Restart VS Code after installing it.

3) In Visual Studio Code press Ctrl + Shift + P to bring up the command palette and then type the following command: Preferences: Open Settings (JSON). This should bring up a JSON file with your VS Code settings.

4) Inside the settings.json file you opened in the last step, add the following lines:

"uncrustify.langOverrides": {
    "apex": "JAVA",
    "apex-anon": "JAVA"
},

"[apex]": {
    "editor.defaultFormatter": "LaurentTreguier.uncrustify"
 },

"[javascript]": {
    "editor.defaultFormatter": "LaurentTreguier.uncrustify"
}

5) Save your settings.json file

6) Press Ctrl + Shift + P to bring up the command palette again and enter the following command: Uncrustify: Create Default Config. After running this command you should see an uncrustify.cfg file in your VS Code project

7) Open the uncrustify.cfg file and update all your settings in it (This is just a nice UI with a ton of different options, so nothing complicated here). Make sure to hit the save button in the top right corner when you are done!

8) Once you finished open a file you would like to have code formatting done to and press Alt+Shift+F

And that’s it boiz and gurlz! Enjoy your auto-formatted code!


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 Tutorial: How to Setup Visual Studio Code for Salesforce Development

Why use an IDE?

First things first… after you use an IDE you will never ask this question again. IT MAKES YOUR LIFE SO MUCH EASIER! Please take the time to leverage an IDE when doing development. Your work will take a fraction of the time it would take otherwise.

Ever wish your code editor would auto-complete method names, field names, object names, etc for you? Well an IDE will do that along with tons of other things that will simply development.

As for why you would pick Visual Studio Code specifically for Salesforce Development, you would do that because it’s an excellent IDE and it’s the only IDE with plugins that Salesforce itself maintains. That’s right, THE ONLY ONE! There are two other big contenders, the Illuminated Cloud 2 for IntelliJ and The Welkins Suite, but the Salesforce Extension pack for VSCode is the only one upkept directly by Salesforce. As such, it has a large team of developers constantly working to keep it up to date and as useful as possible for your work as a developer on the platform.

How do we setup Visual Studio Code for Salesforce Development?

It’s not super complicated, but can be confusing your first handful of times setting things up. Before I get started, if you’d rather read my GitHub wiki on the subject you can find it here.

You first need to install a handful of things if you haven’t already:

1) Install VSCode
2) Install the Salesforce CLI
3) Optionally install Node.js and npm (there are a lot of great packages in existence you can leverage, but we’re not gonna over those here, just know it can come in handy down the line)

After you have installed VSCode and the Salesforce CLI, you then need to open VSCode, click on the extensions icon and search for the Salesforce Extension Pack. After you find the extension pack, install it.

How to Setup a Project (Using the org based development model)

Before I get into this, if you’re not sure what an org based development model is, it basically means your source of truth for your codebase is still your production org instead of a repository. In a later tutorial I will go over how to actually leverage SFDX and a repo based model, but I want to ease people into this and I know from being involved in twenty three different orgs now, the majority of clients are still stuck in the org based model… so we’re gonna start here.

There is one VERY IMPORTANT HOT KEY YOU NEED TO REMEMBER IN VSCODE and that hotkey is the one that brings up the command palette Ctrl+Shift+P. Remember it, love it, appreciate it, don’t forget it (or do and just come back to this article to remember it).

Alright, now that those things are out of the way, let’s go through the steps to setup our project:

1) Bring up the command palette and run the SFDX: Create Project with Manifest command (technically creating it with a manifest is optional these days, but you’ll see why it’s still beneficial later).

2) When prompted, choose the standard template for your manifest file (unless you would prefer an empty or analytics based template). The standard template creates an xml file that would pull all your code from the org.

3) After your SFDX project has been created it’s in your best interest to find the sfdx-project.json file, open it and update the sfdcLoginUrl to have the login URL for your org. Some orgs have MyDomains they have to login through. It’s super useful for those scenarios.

4) After you update the sfdx-project.json, pull up the command palette again and enter the command SFDX: Authorize an Org. This command will ask you what URL you would like to use to connect to your SF org, ask you to enter an alias for your org (this can be anything) and eventually bring up a browser window and allow you to authenticate/login to your org you want to connect to.

5) That’s it, your project is setup! But now how to do we pull in the metadata from our org into our local project? Still super simple, but the next section covers it.

How to retrieve metadata from your org

There are actually two ways to do this, one leverages the manifest file we created earlier when setting up our project and the other uses the org browser. Let’s check out both methods.

Retrieving Metadata from the Org Browser

To the left of your Visual Studio Code workspace, after successfully setting up your project and connecting to your org, you should see a cloud icon. If you click that cloud icon you will bring up the org browser. This allows you to bring up all the metadata in your org. If you hover over a metadata item, to the right of it you will see an icon shaped like a cloud with an arrow. Clicking this icon will allow you to pull the metadata into your local project.

Retrieving Metadata using the manifest package.xml file

Before we get into this, there is an extension called “Salesforce Package.xml Generator” that will make setting up these package.xml files way easier.

This method is very useful if you intend to pull a ton of specific data from your org into your projects consistently. It’s also quite a bit faster than the org browser is in those situations.

To use this method to pull in metadata, do the following:

1) You should see a “manifest” folder in your project. Inside that folder there should be a file called “package.xml”. You can either leave it alone or update the package.xml file to include more metadata types to pull from your org. When you retrieve data in the next step, you will only retrieve data types declared in your package.xml file. For more information please check out the supplementary links section of this wiki article

2) In the command palette run the SFDX: Retrieve Source in Manifest from Org command. This should pull in all the metadata from your org that you outlined in your package.xml file.

Other Useful Things To Setup

The above stuff is the only stuff that’s required to get up and running, but the stuff I outline below will make your life suck way less.

How to get auto-complete to work for object fields

1) In the command palette run the SFDX: Refresh SObject Definitions command so that you can get autocompletion on your object fields.

If you want your SObject definitions to automatically refresh every time you open your VSCode project, do the following:

In the extension settings under “Salesforce Apex Configuration” there is a checkbox for “Enable-sobject-refresh-on-startup”. This automatically refreshes your sobjects from your org when your project is loaded.

How to Auto-Deploy to your org on save

If you didn’t know, by default you won’t auto-deploy to your org when you save your code. You have to right click on your file in the project and select the option that deploys the code to your org. If you want auto-deploy to be setup, follow these steps:

1) In VSCode go to File -> Preferences -> Settings.
2) Click the Extensions drop down
3) Click the Salesforce Feature Previews extension
4) Check the box next to “Push-or-deploy-on-save”
5) It’s also in your best interest to enable the “Detect Conflicts At Sync” feature preview in settings if you use the auto-deploy on save feature. By enabling this you will be informed if your save has any conflicts with other developers code before you actually deploy it to your org.

Still want more info?

In the GitHub wiki article I have even more useful stuff and I update it frequently. Check it out!


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 (LWC): How to Communicate between Aura Components and Lightning Web Components Using Custom Events and the Api Decorator

Why Would You Want to Communicate Between Component Types?

There are a bunch of reasons it’s beneficial to communicate between component types but the most common ones that I have found are the following:

1) You’re building a new component and realize you need functionality that only Aura Components support, but it’s a very small piece of the component. Instead of building the entire thing in an outdated and much less performant Aura Component, you build most of it in an LWC and just communicate to a small Aura component to do the function only it can do.

2) You’re staffed in an Aura heavy org and when you start building new things for the existing Aura components you should build them in LWC. You can easily do this, but you need to know how the communication channels work between component types.

Once you see how easy it is to communicate between components it’ll be much easier to switch to LWC’s to do development for everything moving forward.


How to Communicate from an LWC to an Aura Component

This is super simple but it’s confusing if you’ve never done it before. We’re basically just gonna create a custom event in our LWC and handle that event in the Aura Component. Let’s check out the code and then I’ll explain it a bit:

<!--This is the LWC HTML-->
<template>
    <lightning-input class="dataToSend" placeholder="Enter text to transfer">
    </lightning-input>
    <lightning-button variant="brand" label="Pass data to Aura Component" 
    onclick={communicateToAura} ></lightning-button>
</template>
//This is the LWC JS Controller
import {LightningElement} from 'lwc';

export default class LwcCommunication extends LightningElement
{
    //This method creates a custom event that dispatches itself.
    //The Aura component then handles this event
    communicateToAura()
    {
         console.log('Communicating to Aura ::: ');

         //We are grabbing the value from the lightning input field that has the dataToSend 
         //class
         let dataToSend = this.template.querySelector(".dataToSend").value;

        //We are creating a custom event named senddata and passing a value in the detail 
        //portion of the custom event
        const sendDataEvent = new CustomEvent('senddata', {
            detail: {dataToSend}
        });

        //Actually dispatching the event that we created above.
        this.dispatchEvent(sendDataEvent);
    }
}
<!--This is the Aura Component HTML-->
<aura:component description="Aura_Communication">
	<aura:attribute name="dataReceived" type="String"/>

	<!--The onsenddata is what handles the custom event we made in our LWC-->
	<c:lwc_Communication onsenddata="{!c.receiveLWCData}" aura:id="lwcComp" />
        <p>This is the data receieved from our LWC: {!v.dataReceived}</p>
</aura:component>
({
       //This is the Aura JS Controller
	
        //This method receives data from our LWC and sets the dataReceived
	//Aura attribute with the events dataToSend parameter (this is the name of the 
        //variable we send in the LWC)
	receiveLWCData : function(component, event, helper)
	{
	    component.set("v.dataReceived", event.getParam("dataToSend"));
	}
});

Alright so now that you’ve checked out the code let’s go over this just a lil bit. In the communicateToAura method above you can see that we create a CustomEvent object and we give it the name ‘senddata’, we also pass some data in the custom event by using the detail property of our Javascript custom event object.

Then in the Aura component’s html we can see that we import our lightning web component using this line:

<c:lwc_Communication onsenddata="{!c.receiveLWCData}" aura:id="lwcComp" />

You can see that when we import our lightning web component that we have an onsenddata event that calls a method in the Aura Components javascript controller called receiveLWCData. When you dispatch your senddata event in your lightning web component the Aura component handles it with the onsenddata event attached to the lightning web component.

Finally you can see that we get the data from the event that was passed to us in the receieveLWCData in the Aura Components JS controller. The most important part of the method is the event.getParam(“dataToSend”). You are grabbing the variable that you passed into the detail property of your CustomEvent object in your LWC. Let me put them side by side so you see exactly what I mean:

//LWC Custom Event code
const sendDataEvent = new CustomEvent('senddata', {
            detail: {dataToSend}
});

//Aura code
component.set("v.dataReceived", event.getParam("dataToSend"));

And believe it or not it’s really that simple. You have successfully passed data from your LWC to your Aura component. Now let’s figure out how to do this in reverse.


How to Communicate from an Aura Component to an LWC

Alright so how do we do the exact opposite of what we did above?? It’s pretty simple but we need to leverage the wonderful @api decorator for lightning web components to make this work as opposed to Aura event communication. Alright so let’s check out the code below and then I’ll go over it a bit more in detail:

<!--This is the LWC Template/HTML-->
<template>
	<p>This is the data received from the Aura Component: {dataReceived}</p>
</template>
//This is the LWC JS Controller
import {LightningElement, api, track} from 'lwc';

export default class LwcCommunication extends LightningElement
{
	//Tracked variables ensure that they are refreshed on the page when their values are
	//updated in the code
	@track dataReceived;

	//The api decorator makes this a public method that any component that houses this 
        //component can access/call
	@api receiveData(data)
	{
	    this.dataReceived = data;
	}
}
<!--Aura Component HTML-->
<aura:component description="Aura_Communication">

	<!--The onsenddata is what handles the custom event we made in our LWC-->
	<c:lwc_Communication aura:id="lwcComp" />

	<lightning:input aura:id="dataToPass" />

	<lightning:button label="Pass data to LWC" onclick="{!c.passDataToLWC}"/>
</aura:component>
({
        //This is the Aura Component JS Controller

	//This method sends out data to our LWC from the Aura component.
	passDataToLWC : function(component, event, helper)
	{
		let stringToSend = component.find("dataToPass").get("v.value");

		//We are calling the receieveData method in our Lightning Web Component here
		component.find("lwcComp").receiveData(stringToSend);
	}
});

Alright, so as you can see nothing super complicated just some weird stuff you may not be super comfortable with yet. There are two very important pieces to making the passage of data between components possible.

The first is the @api method in the LWC. The receiveData method has the @api decorator in front of it. This makes the method public available to its parent component regardless of what component type it is.

The second is the component.find(“lwcComp”).receiveData(stringToSend) line in the passDataToLWC method in the Aura Components Javascript controller. This is finding the lwc that we imported into our Aura Component by its aura:id and then calling the receiveData method in the LWC (the method with the @api decorator) and passing it data.

This is surprisingly simple thankfully, no weird hacky tricks necessary just a few lines of code and we’re all good to go! If any of this is super confusing please check out the video above. I go over every aspect of the code in great detail.


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 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