Ad Code

Dynamically create components in salesforce lightning

There will be instances where you need to create lightning components dynamically in Salesforce. In my case, I got a requirement to show the data from different systems(API calls) within the lightning page in the table format. If I use the data-table base component for all the sources, it will be a redundant code.

This is where we can go with a dynamic lightning component feature that makes our code reusable across the application. 

In this post, we will discuss in detail how to create a reusable and dynamic lightning component in Salesforce. 


Step 1: Create a lightning component for data-table 

DataTable.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global" >

    <!-- attributes -->

    <aura:attribute name="data" type="Object"/>

    <aura:attribute name="columns" type="List"/>

    <aura:attribute name="selectedRowsCount" type="Integer" default="0"/>

    <aura:attribute name="maxRowSelection" type="Integer" default="1"/>

    <!-- the container element determine the height of the datatable -->

    <div style="height: 200px" class="slds-m-top_medium">

        <lightning:datatable

                             aura:id="DataTable"

                             keyField="id"

                             data="{! v.data }"

                             columns="{! v.columns }"

                             maxRowSelection="{! v.maxRowSelection }"

                             />

    </div>

</aura:component>

We have to pass columns and data as an input parameter when we create this component dynamically at the parent level.

 

Step 2: Create parent lightning component and add a logic to create the data-table component dynamically

 ParentComponent.cmp

<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" controller="poc" access="global" >

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

    <aura:attribute name="data" type="Object"/>

    <aura:attribute name="columns" type="List"/>   

    <lightning:button label="get accounts" class="" onclick="{!c.GetAccounts}"></lightning:button>

    <div>

        {!v.body}

    </div>

</aura:component>

 

ParentComponentController.js

({

    init: function (cmp, event, helper) {

        cmp.set('v.columns', [

            {label: 'Account Number', fieldName: 'Id', type: 'text'},

            {label: 'Account name', fieldName: 'Name', type: 'text'}

        ]);

    },

    GetAccounts: function (cmp, event, helper) {

        var action = cmp.get("c.getAccounts");

        action.setParams({

        });

       

        action.setCallback(this, function(response) {

            var state = response.getState();

            if (state === "SUCCESS") {

                var result = response.getReturnValue();

                helper.createDynLightningComponent(cmp, event, result);

            }

            else if (state === "INCOMPLETE") {

                // do something

            }

        });

        $A.enqueueAction(action);  

    },

})

 

ParentComponentHelper.js

({

    createDynLightningComponent: function(cmp, event, result){

        $A.createComponent(

            "c:DataTable",

            {

                "columns" : cmp.get("v.columns"),

                "data" : result

            },

            function(component, status, errorMessage){

                //Add the new button to the body array

                if (status === "SUCCESS") {

                    var body = cmp.get("v.body");

                    body.push(component);

                    cmp.set("v.body", body);

                }else if (status === "INCOMPLETE") {

                    console.log("No response from server or client is offline.")

                }else if (status === "ERROR") {

                    console.log("Error: " + errorMessage);

                }

            }

        );

    },

})

$A.createComponent method helps to create the lightning component. Also, we can use it to create other UI elements dynamically.

Dynamic aura component salesforce
As mentioned in the above screenshot, every time user clicks the button, we call the apex class, get the account list and pass it as an input parameter to the DataTable component. 

Try this and let me know in case you have any questions. Appreciate your feedback in the comments section below.

Post a Comment

1 Comments

  1. Hi Naveen K N, can we create a view form or edit form using $A.createComponent method. I am building a record detail page with edit and delete buttons.Can we do this using $A.createComponent method or do we need to use anything else. As I am using without sharing in my controller I should not use recordviewform or edit form. So please let me know whether it is possible to have a record view form using $A.createComponent method. Also when I am replacing input test to output text how can I have a field label

    ReplyDelete