Keep this handy helper available for your Lightning components

I’ve decided to do some write up on Salesforce – especially Lightning development. Lightning is basically Salesforce’s proprietary JavaScript and CSS Framework bundled into one. It’s a component-based system, mobile friendly, with the power of a server side language (Apex), just in case you need it.

In the following tutorials, you might see a “helper.callServer()” method – which I’m outlining below:

If you’re ever going to do some kind of call to an Apex class – this is a must have in your helper. Think of it as sort of like jQuery’s $.ajax() method – but limited to a specific class.

Salesforce has the same exact code in this doc with some explanation, but I wanted to write it up in my own words. Let’s break it down below.

As mentioned, this is what we need to call an Apex class from our components. It is basically a wrapper to an XMLHttpRequest, along with other utilities to make our JavaScript easier.

Again, components are front end code – Apex sits in the server. This method is the communication between the two.

Set up Apex

First, you declare a class. This is done in our .cmp (component) file, way at the top – it looks like below:

<aura:component implements=”…” controller=”MyClass”>

Now we’re set up with an Apex class called “MyClass”. Let’s build that class, with a method called “doSomething()”:

Note the “@auraEnabled” declaration. This allows us to access it from our JavaScript.

With the our helper in place, all we need to do in our controller will be something like below:

You see, our helper had arguments that looked like below:

callServer : function(component,method,callback,params) {…

Which is what we’re doing in our controller. The second parameter “c.doSomething” – is the method in our Apex class. The 3rd parameter “callback” – is an anonymous function that get’s triggered through “.apply()” in our helper. This is executed when our Ajax call finishes. And we’ll have access to the response.

Sending Parameters

You can send information to your Apex class by setting an object to the last parameter called “params”. In our example above, we’re simply passing an empty object “{}”. But in reality, you will most likely send something to the server.

Our method “doSomething” is expecting a string called “input”.

The object we can pass will look like below:

Notice the key “input” must match our server variable “input”.

If you would like to pass another value, simply add another key:

In our doSomething method:

doSomething(String input, String input2)

You can also pass multiple values as a JSON string, so in your controller:

In your class:

So there. This helper + Apex combination will go a long way. I especially like the callback setup where you simply take care of the good response from the server.

Hope this helps.

Leave a Comment.