Get the ID from URL with Apex and Lightning Component

The following steps will help you to get some idea about how to get the id from URL to aura component.

Here, we are not directly passing the id to the aura component.

Yes, Follow the steps to complete the task.

You know what is the task, we are going to show the account record information based on URL id

STEP-1: Create Lightning Application

<aura:application>
    <aura:attribute name="GetIdFromUrl" type=”String” default=”this is default value”/>
    ID from URL : {!v.GetIdFromUrl}!
</aura:application>

STEP-2:  Create Lightning Component (Aura Component)

// Aura Component File

<!
<aura:component controller="AccountFormByIDController" >
    <aura:attribute name="accGetID" type="String"/> 
    <aura:attribute name="ac" type="Account"/>   
    <aura:handler name="init" value="{!this}" action="{!c.doInitAction}" /> 
   <p>{!v.ac.Name}<p>
   <p>{!v.ac.Type} </p>
   <p>{!v.ac.Industry} </p>
</aura:component>

// Aura Controller

({
    doInitAction : function(component, event, helper) {
              var action = component.get("c.find_AccById");
        action.setParams({ "get_accountid": component.get("v.accGetID") });
         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);
    },
})

STEP – 3: Apex Class Controller

public class AccountFormByIDController {
    @AuraEnabled
    public static Account find_AccById(Id get_accountid) {
        if(get_accountid != null ) {
            return [SELECT Id, Name, Type, Industry from Account where ID = :get_accountid];
        }
        else{
            return [SELECT ID,  Name, Type, Industry from Account LIMIT 1];
        }     
    } 
}

STEP – 4: Place the component inside the App file

<aura:application>
    <aura:attribute name=”GetIdFromUrl” type=”String”/>
    Value in GetIdFromUrl Attribute: {!v.GetIdFromUrl}
    <c:AccountByID accGetID=”{!v.GetIdFromUrl}”/>
</aura:application>

Now you can the account record information in your screen 🙂

Leave a Reply

Your email address will not be published.