Passing URL parameters to controller in Lightning components/ AURA

The following example helps you understand how to pass parameters from URL to components.

In AURA/ Salesforce1 platform, it is made easy to pass the parameters to the controllers.

We know that we can create attributes in the components as variables and they are meant for the scope of the components. So we create application attributes for the entire scope of application. So when we need to get the values from the URL, it is easy to pass them to application attributes, in other words, application attributes can take the values from URL directly.

Here is a simple example:

1. Create an application - 'URLApp'

2. Create an attribute in the application XML.
<aura:application>
    <aura:attribute name="fromURL" type="String" default="this is default value"/>
    Value in Attribute: {!v.fromURL}!
</aura:application>
Save the XML and run it, your output should be:


Now, If you just pass a value to the url the attribute as parameter in the URL, for example, in this case:

That's all there is for parameter passing using URL.

Now that you have the value in the attribute, you can play with it. Now let's say, we want to get Account details based on the ID from URL.

Let's create a component and pass this value to the component and we can take it from that easily.

3. Create a component Name: AccountByID, adding a server-side controller, AccountByID, with an attribute: accID
<aura:component controller="AccountByID" >
<aura:attribute name="accID" type="String"/> 
    <aura:attribute name="ac" type="Account"/>   
<aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
  <ui:inputText label="Account Name" value="{!v.ac.Name}"/>            <ui:inputText label="Type" value="{!v.ac.Type}"/> 
<ui:inputText label="Industry" value="{!v.ac.Industry}"/>  
</aura:component>

So with this, Component is capable of showing an account record on the app. we need to associate this component with our app and controllers.

4. Client-side Controller:
({
    doInit : function(component, event, helper) {
     
        var action = component.get("c.AccById");
        action.setParams({ "accountid": component.get("v.accID") });
         action.setCallback( this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.ac", response.getReturnValue());
                console.log(response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
     
    },
})


5. Server-side Controller:
public class AccountByID {
    @AuraEnabled
    public static Account AccById(Id accountid) {
        if(accountid == null) {
            return [SELECT ID,  Name, Type, Industry from Account LIMIT 1];
        }
        else{
            return [SELECT Id, Name, Type, Industry from Account where ID = :accountid];
        }    
    }
    

}
And on the app:
<aura:application>
    <aura:attribute name="fromURL" type="String"/>
 <!--   Value in Attribute: {!v.fromURL} -->
    <c:AccountByID accID="{!v.fromURL}"/>
</aura:application>
  Now, Try without URL parameter:

Now try with URL parameter of ID other than of 'GenePoint':



Update [Dec 25, 2016]:

One of the visitors to this blog, shahjada, asked me a question, well this is indeed a needful enquiry, that how can the parameters in the URL be used if the components are directly referred in the app builder or community builder!!!

I thought there must be a way because I've seen salesforce is doing that using some kind of system/global variables in the community builder:


So using my crazy developer mind, I started creating a component, thinking of testing this idea:

1. getURLParam.cmp:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes" access="global" >
<aura:attribute name="fromURL" type="String" default="this is default value"/>
    Value in Attribute: {!v.fromURL}
</aura:component>
And then I added design component:

2. getURLParam.design:

<design:component> 
    <design:attribute name="fromURL" label="fromURL" description="Give the value here!" />
</design:component>
3. if you want to add svg you can, or else leave it, I added mine a red dot, I borrowed it from bookshelf.

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
     width="400" height="400">
  <circle cx="100" cy="100" r="50" stroke="black"
    stroke-width="5" fill="red" />
</svg>
4. Added this component to one my community:
And remember this step is important, I gave the value in the property, {!myParam}, same as the parameter in the URL which I will use in a moment.

And now the testing time:




This is one way of getting, and there is a lot of other ways using jquery libs or javascript in the controller. I like it this way. Why dont you guys give it a try and let me know what you think!

HTH...
Prabhan

Comments

  1. What if we are not putting component in application and directly want to get param in component? For example, if we build community through napili template you dont need any app but still need to fetch the parameter from url.

    ReplyDelete
    Replies
    1. I have a very good solution for this. I will update the post in some time.

      This is good stuff, thanks for the challenge. :)

      Delete
    2. I Prabhan, Can you please post your solution for this? I am stuck with point mentioned by Shahjada. I am using Napili template and I am not able to use url params in that.

      Thanks,
      Akshay

      Delete
    3. Hey Akshay, I updated the post. look at the recent update.

      Prabhan

      Delete
  2. Hi Prabhan,

    I didnt get the last portion you wrote in red. It doesn't seem to work for me for getting the current page url parameters. Is it still working for you?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. hi What if we want to get multiple parameters from URL?
    how to split them any clue?

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. There's a sample loop here - https://developer.salesforce.com/forums/?id=906F0000000g1blIAA

      Delete
  5. Hi, I have a question about the second approach. Where do you define the logic around the myParam?

    ReplyDelete

Post a Comment

Popular posts from this blog

Lightning spinner inside Button

Nested AURA:IFs in Lightning Components Salesforce