Call Apex or SOQL in just one line from your Lightning Aura Components

You’re not alone.

Luckily, there’s a way to remedy all of that.

Just by adding a utility base component to our code, we can create a way to call Apex or run some SOQL with just one line of code.

A better way of calling Apex and SOQLWith the help of a new “utility” component we’re going to build, our goal is to be able to call Apex using the following lines of code:helper.

apex(component, "getAccounts", { searchstr : searchTerm}).

then(function (result) { //do something with the result})Here, we’re calling the function getAccounts defined on the Apex controller which takes in one parameter called searchStr.

The most significant difference between the new approach and the original approach, as the keen reader might notice, is that the new approach is not 15 lines of boilerplate.

We also want to be able to directly execute some SOQL using the following lines of code:helper.

soql(component, "SELECT Id, Name, AnnualRevenue, Industry FROM Account WHERE Name LIKE '%" + searchTerm + "%'").

then(function (accounts) { //do something about the accounts})Easier to read?.Yes.

Faster to write?.Yes.

Let’s move on to the next section and find out how we can do all of this.

Creating the ApexHelper utility componentThe above can be accomplished by creating a small utility component that defines the apex and soql functions.

First we’ll create a new Lightning Component and name it ApexHelper.

This component will contain a component body and also contain some code in the helper JavaScript file.

Additionally, we will also create an Apex Controller for this component called ApexHelperController.

I created a Gist showing all of the code we need to put together along with a sample of how to use it:Once you’ve created this utility component along with the associated Apex controller, you can start using the helper.

apex and helper.

soql functions in any component you have, provided that your components inherit from the new utility component.

If you already have a base component in your org, you can either have the base component extend the new component or add this code directly into your base component.

In order to have your components inherit from our new utility component, you just need to add the extends="c.

ApexHelper" attribute to the aura:component tag:<aura:component extends="c:ApexHelper">Finally, here’s a gist showing in detail how we can use these utility methods in our components:One note when trying to use these utility methods inside of a helper: we use helper.

apexwhen calling the utility functions from a JavaScript controller, but we would need to use this.

apex and this.

soql if we want to call these utility functions inside of a helper.

Do you think this is something that would make it easier to call Apex or SOQL from your lightning components?.Please let me know your thoughts.

.

. More details

Leave a Reply