How to send parameters in AuraEnabled methods in Salesforce Lightning Components

How to send parameters in AuraEnabled methods in Salesforce Lightning Components?

How to send parameters in AuraEnabled methods in Salesforce Lightning Components?

Passing value to and fro from the Lightning component is one of the task which is done on day to day basis, this post deals with the concern that how to pass values from the client side Javascript controller to the AuraEnabled Apex Controller at server side.

Salesforce Lightning Training

Passing values from client side needs the following requirement as mentioned below :

  1. An attribute in the component mark up to hold the value which is sent.
  2. An AuraEnabled Server side controller method that accepts the value.
  3. A JavaScript controller on client side to send the value from client side to server side.

Below is an example of a simple component which contains a string attribute and its javascript controller sends this attribute to the server side controller, where this controller perform some basic task on it.

Component’s mark-up is below

<aura:component controller=”serverSideCntrllr”>

  <aura:handler name=”init” value=”{!this}” action=”{!c.callingServer}”/>

  <aura:attribute name=”myAttribute” type=”String” default=”Hello World”/>

</aura:component>

JavaScript controller Code is given below

({

                callingServer : function(component, event, helper) {

          var myAttribute = component.get(“v.myAttribute”);

          var action = component.get(“c.setAttribute”);

          action.setParams({ “myString” : myAttribute });

          action.setCallback(this, function(response) {

        

            var state = response.getState();

            if (state === “SUCCESS”) {

              // Do stuff

            }

            else {

              console.log(state);

            }

          });

          $A.enqueueAction(action);

                }

})

Server side AuraEnabled Code is given below

public class serverSideCntrllr {

    @AuraEnabled

    public static void setAttribute(String myString) {

      System.debug(myString);

    }

}

In the example above, we can see that the type of the attribute sent is basic string type, therefore when this value is passed to the server side controller than it works fine, but this is not the case for each data type. You have to perform few tweaks before you can send the value and sometime you have to perform some actions after the value is received at the server side. We will see these tweaks in below examples.

Passing Integer as a value from client side server.

Integer

Interger is value which is a basic type and easily passed from the client side without making any changes, but at the server side we need to first convert this value into integer and then we can perform the numerical task related to the integer, as shown below in the example.

First define an integer type attribute in the component as shown below.

<aura:component controller=”serverSideCntrllr”>

  <aura:handler name=”init” value=”{!this}” action=”{!c.callingServer}”/>

  <aura:attribute name=”myAttribute” type=”String” default=”Hello World”/>

  <aura:attribute name=”IntegerVar” type=”Integer” default=”1″/>

</aura:component>

Then make the change in the JavaScript Controller as shown below.

({

            callingServer : function(component, event, helper) {

          var IntegerVar = component.get(“v.IntegerVar”);

          var action = component.get(“c.setInteger”);

          action.setParams({ “myInteger” : IntegerVar });

          action.setCallback(this, function(response) {

        

            var state = response.getState();

            if (state === “SUCCESS”) {

              // Do stuff

            }

            else {

              console.log(state);

            }

          });

          $A.enqueueAction(action);

            }

})

Then the AuraEnabled method as shown below.

@AuraEnabled

    public static void setInteger(String myInteger) {

      System.debug(myInteger);

    }

This code runs fine when we execute the system.debug statement but, when we try to perform a numerical operation, this method will start producing the following error : FATAL_ERROR Internal Salesforce.com Error.

myInteger++;

We are facing this error because, it is due to the improper casting of the integer variable by the framework. Therefore before we could use this variable as an integer, we need to first cast it into the correct type as shown below.

myInteger = Integer.valueOf(myInteger);
myInteger++;

This is a good work around till the framework does not address this issue.

sObject

sObjects are easy to send and receive between server side and client side controller everything is handled perfectly by the framework and we do not need to worry about any casting related issue with sObject.

The only issue is that the relationships are not available in the apex method and with the new lightning data service, we might not even have to query the record anymore.

Date

You will not be able to send Date variable as a value in the client side controller, in this case we have to tweak this data type at client side and then pass it to server side controller and then again cast it to date at the server side controller.

Create the Date attribute at the component as shown below.

<aura:attribute name=”myDate” type=”Date” default=”1981–08–26″/>

Javascript controller as shown below.

({

            callingServer : function(component, event, helper) {

          var myDate = component.get(“v.myDate”);

          var action = component.get(“c.setInteger”);

          action.setParams({ “myInteger” : JSON.stringify(myDate ) });

          action.setCallback(this, function(response) {

        

            var state = response.getState();

            if (state === “SUCCESS”) {

              // Do stuff

            }

            else {

              console.log(state);

            }

          });

          $A.enqueueAction(action);

            }

})

Server side controller as shown below.

@AuraEnabled
public static void setDate(String myDate) {
Date myNewDate = Date.valueOf(myDate);
}

Apex Classes

The next encounter with error would be when you are going to send a wrapper class as an argument from client side to server side, in this scenario we have to make tweak in the value passed both at the client side and as well as at the server side.

To test this we first create a wrapper class as shown below

public class NewTestWrapperClass {
@AuraEnabled
public String label {get; set;}
}

Then we first create a component attribute as an apex class.

<aura:attribute name=”myClass” type=” NewTestWrapperClass” />

Normal javascript Controller would be

({

            callServer : function(component, event, helper) {

      var myClass = component.get(“v.myClass”);

      var action = component.get(“c.setClass”);

      action.setParams({ “myClass” : myClass });

      action.setCallback(this, function(response) {

        // Do stuff

      });

      $A.enqueueAction(action);

    }

})

And Apex Controller method would be

@AuraEnabled

    public Static void setClass(NewTestWrapperClass myClass) {

      System.debug(myClass);

    }

But this would lead to the fatal error and we would not be able to find the desired output. The best work around to this situation is to convert the argument into the relative JSON string and then Deserialise this string in the Apex Controller at the server. We convert the wrapper class object into the JSON string by using the Javascript method JSON.stringyfy as shown below

({

            callServer : function(component, event, helper) {

      var myClass = component.get(“v.myClass”);

      var action = component.get(“c.setClass”);

      action.setParams({ “myClass” : JSON.stringify(myClass) });

      action.setCallback(this, function(response) {

        // Do stuff

      });

      $A.enqueueAction(action);

    }

})

And the tweak performed at the server side would be something like this.

@AuraEnabled

    public Static void setClass(NewTestWrapperClass myClass) {

      NewTestWrapperClass nwc = (NewTestWrapperClass)JSON.deserialize(myClass, NewTestWrapperClass.class);

    }

So if you faced a problem similar to the one mentioned above then you have workaround till the framework fixes the issues.

Happy Coding.

Also, Have a look at the below resources:

  1. Best Salesforce Interview Questions book with Apex and Visualforce concept explained

Also, Have a look at the below learning resources:

  1. SOQL (Salesforce Object Query Language)

  2. Apex Trigger Best Practices and the Trigger Framework

  3. Salesforce Interview Question and Answers Part 2

  4. Salesforce Interview Questions on Test Class

  5. Salesforce-lightning-interview-questions-2018

     6. Salesforce Interview Questions Batch Class 

Sumit Datta

Sumit Datta

I am a 5x Certified Salesforce developer with overall 7 years of IT experience and 5 years of Implementation experience in Salesforce. I am here to share my knowledge and help Beginners in Salesforce to understand the concepts of Apex, Visualforce, Salesforce Lightning and Salesforce Configuration.

Leave a Comment

Your email address will not be published.