Salesforce Apex Master Class (Ep. 4) – What is an IDE?

What is an IDE?

Let’s review what an IDE is and why it’s so incredibly helpful to you as a developer in Salesforce and beyond. As a developer, you’re encouraged to use an IDE, since it can make your work so much easier.

An IDE is an integrated development environment, where you can combine a wide variety of development tools to do your work much faster and more efficiently every day. Now, let’s check out an example (below) of an IDE at work. This particular IDE is IntelliJ, and I’m using a plug-in that allows me to do Salesforce development called the Illuminated Cloud 2 plug-in.

Demoing the Benefits of Using an IDE

An IDE like IntelliJ here will make your life, and the lives of your developer teammates, so much easier. In this interface, I have my code editor so I can write Apex code or a lightning web component, among other things. I can also analyze debug logs here in this IDE, or even run anonymous Apex. But why should you use an IDE and not just a developer console? An IDE like IntelliJ has many features that developer consoles don’t.

The first major benefit is if you want to know everywhere that a class is used in your codebase, you can simply copy the name of the class, then press CTRL-shift-F, and then the IDE searches for the class in all of the code in your Salesforce environment. There are also a litany of other hotkeys that will make traversal through your code base considerably easier. Shortcuts like that aren’t available in the developer console.

Autocomplete is another major advantage in using an IDE like IntelliJ with Illuminated Cloud 2. You can type “system.” and the IDE knows methods are available for that system class in the Apex language. So, you it will present to you a list of autocompleted methods that you can select from and have your code auto-completed for you. By contrast, the Salesforce developer console’s auto-complete features struggle and sometimes just outright do not work. This makes it easy for programmers, like you, to know all your options without having to look them up elsewhere in documentation.

There’s even more an IDE can do for you. For example, you can enable version control, allowing you to create local backups of your code, so you can revert back if something goes wrong. You sure can’t do that in a developer console! Meanwhile, you can find more useful stuff in the settings menu too, such as setting all the defaults for code style for a specified language, such as Apex or Javascript. All that will be automatically formatted for you. You can export all this to other developers on your team too, and make everyone’s code consistent. That’s an example of the convenient, time-saving efficiency of an IDE.

Another option is to run your Apex tests in the IDE, and it will display coverage next to the classes that it tests. Yes, you can do that in developer consoles too, but an IDE like IntelliJ will conveniently show you which classes the test covered, and even break down what happened in those tests, such as line coverage. Pretty cool, huh? And this is just the start; an IDE can do a whole lot more!

To recap, an IDE like IntelliJ will make your life as a programmer faster, more convenient, more direct, more consistent, and more intuitive than ever before, acting like a souped-up developer console with more options so you can get more work done. Give it a try, and see what you can accomplish with the power of an IDE! 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. 3) – What is the Apex Programming Langage?

The Salesforce Definition of What the Apex Language is

Let’s go over what Apex actually is, and when you, as a developer or administrator, should use it when creating custom functionality in your Salesforce orgs.

Apex is a proprietary development language created specifically for Salesforce’s own platform. Apex looks and feels similar to Java (not Javascript) or C#. The Apex language allows you to build custom functionality that Salesforce’s point-and-click tools can’t support or do on their own. This means that with Apex, you can expand Salesforce’s functionality and build absolutely anything that you or your users can dream up for your Salesforce instance. The sky is the limit with the power of Apex! Go ahead and give it a try, and see what you can do with it.

A Simpler Explanation of What the Apex Language Is

Apex is a strongly typed object-oriented programming language, but what does that really mean? Let’s look at an example.

public class OpportunityCalculator {
    
    Integer numberValue = 1;
    String oppName = 'Cool Opp';
    
    
    public Integer addOpportunityValues(Integer oppValueOne, Integer oppValueTwo){
        Integer oppValuesCombined = oppValueOne + oppValueTwo;
        return oppValuesCombined;
    }
    
    public Integer substractOpportunityValues(Integer oppValueOne, Integer oppValueTwo){
        Integer oppValuesCombined = oppValueOne - oppValueTwo;
        return oppValuesCombined;
    }

This example is a representation of a calculator for opportunities in our org. Like a real, physical calculator, this code calculator could potentially have the ability to add, subtract, multiply, and divide value. My opportunity calculator class above uses methods to add and subtract values, all while creating a representation of an object and the many ways in which that object can interface with its users (such as pressing a calculator’s buttons to do some math). There’s much more I could say about object-oriented programming, but that can should probably wait for a future blog post. It’s too much to unpack here, but eventually, we’ll check it out together!

There are four key things you need to know about object-oriented programming: encapsulation, abstraction, inheritance, and polymorphism. If you’d like to know more about those four in greater detail, check out my video over OOP in Apex here!


What is a Strongly Typed OOP Language?

public class OpportunityCalculator {

Integer numberValue = 1;
String oppName = 'Cool Opp';


public Integer addOpportunityValues(Integer oppValueOne, Integer oppValueTwo){
Integer oppValuesCombined = oppValueOne + oppValueTwo;
return oppValuesCombined;
}

public Integer substractOpportunityValues(Integer oppValueOne, Integer oppValueTwo){
Integer oppValuesCombined = oppValueOne - oppValueTwo;
return oppValuesCombined;
}



At a very high-level, object-oriented programming (OOP) is the representation of an object and its functionality in code. Now, what is a strongly typed language? First, consider variables, or a way to represent a value. When I create a variable called numberValue and I set it equal to 1, I’m declaring that variable as an integer, or a way to declare a number in Apex (among many other development languages). I’m declaring it as type Integer, but note that if I just declared that 1 as a number value without “Integer,” Apex wouldn’t accept it, nor would Apex allow me to save it like that. In short, Apex needs me to specify the type of value I’m trying to store: Integer. I must also specify what kind of value I want to return from those methods if I want to return something.

So, when I declare my method, I’m saying that when my method is done executing, it will return an integer. In programming languages that aren’t strongly typed, you don’t have to declare variables as a specific type (like Integer). Javascript is an example, where you can simply say that the variable you’re declaring equals 1 or Cool or whatever you can think up, and you don’t define a type for those variable.

In short, strongly typed OOP language means you’ve got to tell the code what it’s supposed to return and what your variable types are.


When Should You Actually Choose to Use Apex?

When exactly should you use the Apex development language? It’s a bit subjective, but also not. Often, you’ll find that out-of-the-box, point-and-click Salesforce stuff doesn’t work well with what your users actually need so they can do their job, and that’s when you use Apex. As a Salesforce user or admin, you must know all the administrative capabilities and know how to create new objects with their own fields, among other things. This is so you know when it’s proper to use administrative tools, or when you should use custom development instead.

Usually, you’ll need to use Apex development in one of two different scenarios. The first is, as mentioned earlier, when your out-of-the-box, point-and-click tools aren’t enough to build what you’re trying to make for your users. The second is when your org scales up to a huge size with lots of users (such as the 500-user mark), where your point-and-click tools can’t handle the sheer volume of daily transactions your users are making. When you reach that point, it’s time for Apex code to take over and work its magic!


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: How to use Named Credentials to simplify your Apex Salesforce Integrations

Why should you bother using Named Credentials?

In short, it’s gonna save you a bunch of time, code and unnecessary configuration, especially when you are authenticating using OAuth. Named credentials basically simplify the authentication portion of your callouts to to external services and allow you do it declaratively through configuration. No matter how hardcode a dev you are, they are 100% worth your time and effort to learn how to use. I promise.


How do you setup a named credential?

You traverse to Setup -> Named Credentials to setup the named credential of your choosing. Named Credentials allow you to authenticate via the vast majority of the authentication methods used by external service providers. You will likely even be able to connect to your internal data bases via named credentials as well if you need to. I’m not gonna go over them all individually in this article. In the video above I got over three different Named credential types and how to configure them. If you’re interested in that portion, please check it out!


How do we reference named credentials in the code?

This literally could not be easier. In fact it’s so simple I think it confuses the hell out of some people, lol. I will give you a simple example below that connects to GitHub via OAuth:

public class GithubOAuthCallout {
    
    public static void callGitHub(){
    	HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:GitHub_OAuth/users/Coding-With-The-Force/repos');
        req.setMethod('GET');
        req.setHeader('Accept', 'application/json');
        req.setHeader('Content-Type', 'application/json');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        System.debug(res.getBody());
    }
}

There are a couple of important things to point out in the code above:

1) When we are setting the endpoint for the HttpRequest we are add the value ‘callout:GitHub_OAuth’ this is how we reference our Named Credential. When you are setting your endpoints for your HttpRequests you pass in your Named Credential by using the following format: callout:[The name of your named credential].

2) If you’ve ever requested data using OAuth authentication you know that we seem to be missing a few steps… We’re not calling out to any authorization endpoints or getting an access token anywhere in the above code. We’re also not setting an authorization header parameter. THAT’S BECAUSE SALESFORCE DOES IT ALL FOR YOU AUTOMATICALLY! Yes… you read that right, automatically, no need to write that code yourself. That ‘callout:GitHub_OAuth’ is doing a ton of behind the scenes magic. It gets that OAuth token for you and automatically sets the authorization header parameter with that token. So wyld right?

Hopefully just that simple example above makes you think twice about choosing to not use named credentials… and if it doesn’t, you probably haven’t done many integrations with external systems yet and don’t realize how much time this saves. IT SAVES A TON OF TIME, CONFIGURATION AND CODE! Trust me on this one. I promise I’m not selling you garbage here. It’s worth using 100% of the time.


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