Design Patterns in Salesforce (Ep. 1) – What Are Design Patterns?

When Should You Learn About Design Patterns?

When you first start learning about software development, I’d recommend against beginning with design patterns. Why? If you start with design patterns, you might be misled and start thinking that all of your code must conform to a design pattern, which isn’t the case and makes the process of learning how to code even more complicated. You’ll end up confused and overwhelmed, and your code could end up overengineered and wonky.

Instead, I encourage you to start with the basic building blocks of code, and design a few applications without using any design patterns, and that can serve as a foundation for more advanced functions, such as design patterns, later on. After you’ve mastered the basics of coding, and experienced a handful of difficult development situations, you’ll be ready to go back and learn about design patterns, and use them to solve tricky and difficult problems or situations in the code you develop.

Also, I recommend you learn more about design principles before getting into design patterns since those principles guide the design patterns. Design patterns will make much more sense once you’ve got a handle on the underlying design principles. To learn more about design principles, you can also check out the book Clean Code by Robert Martin, a fantastic resource for any budding code writer.

What Are Design Patterns?

Once you’re comfortable with the basics of coding and design principles, it’s time for the third step: understanding design patterns! True to their name, design patterns are coding patterns that can help you fix tricky situations you’ll find yourself in while coding, but that’s just the start. Design patterns can also make your code more flexible and easier to read, and be more performant when you’re done writing it.

Suppose you wrote something, and it always takes 2-3 minutes to load. You might be able to use the Singleton pattern to only load something that is very time-consuming once, which will likely cut down on the page-load time. And that’s just one example. Design patterns use their patterns to fix practically any problem or mess you’ve got in your software, and certain design patterns can be prescribed for certain coding issues.

You can think of them as medicine for your code, such as a doctor prescribing either Advil, Tylenol, or Ibuprofin for your headache. Any three of those would work 90% of the time for your headache, and in the other 10%, you may need to try something else. It’s the same with design patterns; none of them is a guaranteed miracle fix for a coding issue, but they generally work, and a skilled developer can prescribe one for a development problem.

Which Design Patterns Should You Learn?

Make no bones about it: there are a lot of design patterns out there! I couldn’t possibly list them all. For now, though, we can narrow the field down to 23 particular design patterns that are best learned first, and they are widely used, too (and they’re well-regarded, too). They are described as the “gang of four” design patterns since they were designed by a quartet of people calling themselves the gang of four. They even wrote a book together on this topic titled Design Patterns: Elements of Reusable Object-Oriented Software. You can check it out to get plenty of in-depth information.

These 23 design patterns are sorted into three categories: behavioral design patterns, creational design patterns, and structural design patterns. These include design patterns that you’ve probably heard of before, such as the Singleton pattern or the Observer pattern. Remarkably, these design patterns are almost 30 years old, but are still in use today, proving just how well-designed and universal in usage they are.

Later in my series, we will review all 23 of those design patterns and how to implement them in your own code. We will also go over some basic areas of object-oriented programming, just in case you’re not familiar with that topic, along with inheritance, encapsulation, and polymorphism.

That’s all for now. I hope that in the future, you’ll master all 23 design patterns and put them to work in your own development tasks and see for yourself just how handy they can really be! Until next time!

Get Coding With The Force Merch!!

We now have a tee spring 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 Coding With The Force Merch 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
Apex Design Patterns Book

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture
Design Patterns: Elements of Reusable Object-Oriented Software Book

Salesforce Apex Master Class (Ep. 2): How to Set Up a Free Salesforce Developer Org

Welcome to the second episode of my Salesforce Apex Master Class! Today, I’ll show you how to set up your own Salesforce developer org!

How to Set Up a Free Dev Org!

It’s easy to set up your own Salesforce developer org, even if it’s your first time using the Salesforce platform. First, you’ll visit developer.salesforce.com/signup, then fill in your information and dive right in. It’s quick and easy, but take note that with Salesforce, you’re living in “the cloud” (aka sharing space on a server with other businesses), and there are limits imposed on your orgs because of that! Limits are imposed on things like, the amount of data you can store in your org or the number of queries you can do in your org in a single execution context.

In your developer org, those numbers tend to be pretty low compared to what you’d experience when using regular organizations. I’ve found some ways to bypass those limits, such as with “big objects”, but I probably should not suggest them as they certainly aren’t “best practice” and I’m not sure Salesforce would condone them!

One note when signing up for Salesforce: if you’ve ever created a Salesforce org or if you’ve been placed in a Salesforce org before, and you used your email address as a username in those orgs anywhere at all, you can’t reuse that email address (usernames must be unique across ALL instances of Salesforce in existence, not just your own org). Instead, you’ll make up something new, or a least revise your email address when using it as a username. Such as adding a few letters or numbers at the end.

Once all that’s done, you’ll receive an email that will inform you that your Salesforce org has been created for you! It’ll take a few minutes to get that email, though, so be patient. Next up, you’ll verify your new account via that email you just received. You’ll click “Verify my account” and set up your password. Once all that’s done, you’ll be looking at your very own Salesforce org, and you’re ready for work! It’s quick, easy, and doesn’t cost you a dime.

That’s all for now. Thanks for reading, and happy coding!


Get Coding With The Force Merch!!

We now have a tee spring 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 Coding With The Force Merch 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
Apex Design Patterns Book

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture
Design Patterns: Elements of Reusable Object-Oriented Software Book

Salesforce Apex Master Class (Ep.1): What to Expect to Do as a Salesforce Developer

What is Salesforce?

You may have heard of Salesforce before, and that developers on this platform get paid good money, but what exactly is Salesforce, anyway? No matter how much you earn, your work will suffer unless you actually enjoy what you’re doing. So before you dive into this career, let’s discover what Salesforce is and what you can expect to do as a developer on the platform!

Salesforce is a customer relationship management (CRM) platform, a vital tool for marketing sales, commerce, service, and IT teams to work in unison and be of service to their customers anywhere and everywhere. As of this writing, Salesforce stands as the #1 CRM platform available, overtaking competing platforms such as Siebel, Oracle, and SAP, among others. For context, CRM’s market share in 2015 was 19.7%, and as of today, it rose only slightly to 19.8%, with minor fluctuations. Meaning, CRM and Salesforce are probably going to remain steady for the foreseeable future, though there’s no guarantee of that. If you’re entering the Salesforce Ecosystem just because it’s the #1 CRM platform, don’t bank on that, even though it hasn’t for awhile, it could shift at any time. At one point (not long ago) Siebel was the #1 CRM platform, now you rarely hear of them.

That said, whether or not Salesforce stays at #1, it’s an outstanding platform that can do you a lot of good, and if you know your stuff, it could pay off handsomely. Now let’s go into more detail.


What You Will Likely Build as an SF Dev

As mentioned above, you’ll most likely use Salesforce for work in IT, marketing sales, commerce, services (such as help desk services), and a few others. IT, marketing sales, commerce, and services are probably going to be the central core of your work, with a few exceptions, so those are a good starting point for your use of Salesforce. Personally, I worked on 50 projects for 20 different clients using Salesforce, nearly all of them involving IT, marketing sales, commerce, and services.

So, what can you expect to build? You could build configuration point-and-click administration stuff and custom development in those areas described above, for example. I built extremely customized sales cloud instances and very large custom marketing applications that can sit on top of Salesforce or to be within a particular organization’s instance, just to name two examples.

Your overall goal: to take a client’s older or underperforming platform and upgrade it with Salesforce. This work can be done pretty quickly, too, and Salesforce’s brand prides itself on that fact. Once your work is done, any team working in IT, marketing sales, commerce, and services can coordinate their work and do it faster, more easily, and with better analytics with their daily work.

With that in mind, you might expect to move into Salesforce pretty quickly for two reasons: one, because of Salesforce’s reputation for speed, and two, because Salesforce offers a huge shell for making it easy for devs to get their work done faster than ever. Along the way, you’ll also want to understand Salesforce’s administrative side, through which you will build database tables, and set up anything else you’d have to develop on your own. When you use Salesforce, a lot of the work is already done for you.

In short, it’s incredibly important for you to get a handle on all this admin work with Salesforce. Some might disagree, which is fine, but having worked as a Java and PHP developer myself, Salesforce’s admin features can cut out a lot of clutter for developer work so I can focus on what matters most: writing code. I greatly enjoy Salesforce’s streamlined feel for my development work, and it was an easy and enjoyable transition to this platform while cutting out time-consuming remedial work. Perhaps the same will be true for you, too!


De-Mystifying Some SF Dev Misconceptions

You might have heard some misconceptions online about Salesforce, such as people saying that you don’t have to write much code with Salesforce, or that outdated languages are being used with it, or that there are few customization options with this platform, among other issues. Those were somewhat true in the past (and still a bit true today), but Salesforce is stronger and more effective than these rumors would suggest. Let’s review.

Salesforce didn’t have much IDE support early on (I have a separate video on the topic), but fortunately, IDE support is everywhere today. Meanwhile, maybe you’ve heard that you can’t do source-driven development in Salesforce, which would be a serious issue. Good news: you absolutely can use source-driven development with Salesforce, such as with scratch orgs, if a developer wants to.

As for outdated programming languages: yes, you’ll use the slightly dated language Apex, which can be compared to what Java was like 6-7 years ago. But don’t let that discourage you! No matter its age, Apex provides nearly everything you need for work in Salesforce, just lacking a few of the most advanced capabilities of coding languages. If that’s ever a concern for you, try using open source repos to fill in the gaps.

Another rumor says that with Salesforce, you can’t work with modern front-end technologies. Up until two years ago, that was true, but with today’s lightning web components, you can pretty much perform whatever modern UI front-end development you need.

The only caveat to working with Lightning Web Component’s within Salesforce is lightning locker service, among a few other issues. Locker Service, which is due for an update soon which might render this sentence incorrect, makes it challenging to use outside JavaScript Libraries. Many JS Libraries that you could easily import into a Node JS project (or equivalent) would require you to re-write some of its code (or a lot of its code) just to get it to function inside of an LWC due to Locker Service restrictions.

Typescript also won’t work out very well in Salesforce, for example, being hampered by a variety of problems. While it can be done there is just so much out-of-the-box Salesforce stuff that it won’t cooperate with that it renders it fairly useless.

As a developer, you’ll have endless options with Salesforce, and I myself have made hundreds of custom applications with Salesforce. You’ll simply have to keep those limitations in mind and plan accordingly. Once in a while, for example, you might build an application elsewhere, such as with AWS, then pipe it into Salesforce. Anything you can’t make in Salesforce, you can just slot right in.

On a final note, some folks might think that anyone who’s using Salesforce is mostly an admin, just doing point-and-click stuff instead of coding. This is simply not true, as a developer on the platform you’ll be expected to do development every single day. I’ve been a developer on the Salesforce platform for the past seven years, I’ve done development work every single day. Coding comes first and foremost with Salesforce as a developer on the platform, I can assure you, and it’s simply a pleasure for any developer like me to use.

Salesforce, in short, isn’t for everyone, but for the right developers, it’s a dream come true. Give it a try, and see what you can create! Until next time!


Get Coding With The Force Merch!!

We now have a tee spring 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 Coding With The Force Merch 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
Apex Design Patterns Book

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture
Design Patterns: Elements of Reusable Object-Oriented Software Book

Salesforce Development Tutorial (LWC): How to use Data Attributes to easily pass data from your component HTML template to your JavaScript Controller

What are Data Attributes and Why Should I Use Them?

Data attributes are a truly magical thing that will, at some point, get you out of some prickly situations as a front end developer. They are essentially a way of storing data on an html element so that when a JS event gets fired your JS controller can easily get access to the data on the HTML element that fired the event.

This is especially useful in scenarios where you want to use for:each templates to generate tables, tabs or whatever else on the screen.


How to use Data Attributes (Example Code and Explanation)

Using data attributes is easy peasy lemonnnnnnnnnnn squezzyyyyyyyy… I’m sorry, it just felt right. Seriously though, it’s easy. Let’s first take a look at how we setup our HTML Template to use data attributes on a button element.

<template>
<lightning-button onclick={getDataAttributes} label="Click Me Bruh" data-donkey="donkeysAreKewl" data-turtle="NinjaTurtles"></lightning-button>
</template>

You see those weird attributes on my element? The “data-donkey” and “data-turtle” attributes? Those are data attributes and as you can see they can be named anything! However they must be in this format: data-randomnameyouchoose. Anything can come after the “data-” when setting up the data attributes on your element (do make sure each attribute has a unique name though!). Pretty cool right? The best part comes next though! Let’s check out the JavaScript Controller’s getDataAttributes method.

import {LightningElement} from 'lwc';

export default class LwcDataAttributes extends LightningElement {
	getDataAttributes(event){
		console.log('This is the data set ::: ' + 
                JSON.stringify(event.target.dataset));
		console.log('This is the data set turtle ::: ' + 
                JSON.stringify(event.target.dataset.turtle));
	}
}

You see that console log that has the “event.target.dataset” value in it? That event.target.dataset produces a Map that houses all of your data attributes in it. The output looks like this:

{"donkey":"donkeysAreKewl","turtle":"NinjaTurtles"}

As you can see it’s a key value pair, the key is whatever you named your data attribute on the HTML Element (notice the data- is excluded however) and the value is whatever value you assigned to that element on your HTML Element.

Now, you may also noticed in the console log below that one that we have the “event.target.dataset.turtle”, this line directly accesses the “data-turtle” value so it will just output “NinjaTurtles”. Pretty niftyyyyy! If you used event.target.dataset.donkey you would get the “donkeysAreKewl” value.

And to be honest that’s really all there is to it, there is one other quick thing we should review though.


What is an Event and the Difference between event.target and event.currentTarget

Boy oh boy does this really confuse people, so let me break it down right quick. Whatever element has the JS event attached to it is the one sending the event parameter to your JS method when you trigger the event (for instance when you use an onclick JS event on an HTML element and then click it to invoke the JS method). THIS IS IMPORTANT! I say this because, it is… trust me, but more importantly you can get into some tricky situations with event.target and event.currentTarget.

The key difference here is that event.target is the TRUE TARGET OF YOUR CLICK! and event.currentTarget is the ELEMENT THAT FIRED THE JS EVENT!

Even if you’ve never done it, you can sometimes wrap multiple elements within a div, and that div is actually the one that houses the onclick event. If you click a button within that div, the button is the “event.target” and the div is the “event.currentTarget”. Be wary of this! If you start to see null values or values you don’t expect in your dataset in your JS controller, this is more than likely why! It has confused many a person (including myself), so just make sure you are paying close attention to which target you are using in your controller.


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