Lightning · Salesforce

Dynamic Reusable Lightning Table Component

Don’t Repeat Yourself (DRY) is a principle of software development aimed at reducing repetition of software development patterns. Most of the time we will find creating same kind of Component for different object over and over again. To over come this we have created Dynamic reusable lightning component.

Github Link :

This component is for displaying the record in a table format, that allow sorting on header fields (without using any extra libraries) and the table is having fixed header and scrolling enabled. This component runs on standard as well as custom object.

To DO :

  1. Create Apex class :(Name It as you Like) -> Copy Paste entire Apex code
  2. Create Lightning Component -> Copy Paste entire component code , don’t forget to change the controller name to your apex , otherwise I am not responsible for the error.
  3. Controller will be automatically calculated, so no problem ,Copy Paste controller.js code , change the action,setparam() -> according to  your object and field to display.
  4. Preview as simple as that.

Overview of this Component:
Apex Class : Table Class
Method : Get_Record_For_Table_Input_From_Query(String objectName,String queryFields,String fullQuery)
Return : Object that can be displayed on Table
objectName = Name of the Object.
queryFields = Fields we want to display.
fullQuery = Full Soql Query.

Call this method and this will return data necessary for the table to be displayed.

Screen Shot 2018-04-25 at 7.10.29 PM

Code :
Apex Class :

public class DynamicTableClass {

    public static object Get_Record_For_Table_Input_From_Query(String objectName,String queryFields,String fullQuery)
        Integer headerindex=0; 
        TargetTable TargetTable_inst = new TargetTable();
        List allListOfRecords = new List();
        String Query=fullQuery;
        //split all the fields into a list of strings
        List fieldList= queryFields.split(',');
        //Creating a Dynamic Object Type with Custom object name
        String listType = 'List';
        //Creating a Dynamic Record Type with Custom object name
        String EachRecordType =  ''+objectName+'';
        //Creating a generic Sobject to hold data of custom object
        List ListOfRecords = (List)Type.forName(listType).newInstance();
        SObject IndividualMember = (SObject)Type.forName(EachRecordType).newInstance();
        //Execute the Query to get and store the data in Generic object
        ListOfRecords = Database.query(Query);
        //object field map
        Map objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
        for(Integer i=0;i<ListOfRecords.size();i++)
                IndividualMember = ListOfRecords[i];
                EachRecord Each_record_nested_List_Of_Fields = new EachRecord();
                List temp = new List();
              for(String field :fieldList)
              {   //record id
                  //if there is any relation like
                      List relation = field.split('\\.');
                      //get the actual value not id in relation
                  {		//except is store all field and values
        //prepare header
        List<header> headerList = new List<header>();
        for(String field :fieldList)
            header h = new header();
            String s = field;
            //removing __c
            Integer i=s.lastIndexOf('_');
            //replacing _ with space so we get account_name = account name
            s=s.replaceAll('_',' ');
        return TargetTable_inst;
public class header{
        @AuraEnabled public String name; //Name of the Field
        @AuraEnabled public String api;  //Api of the Field
        @AuraEnabled public Integer sorted; //Is the FieldSorted
        @AuraEnabled public Integer index; //Index of the Field on record
    public class EachRecord{
        @AuraEnabled public Map fieldValuePair; //The field and Its corresponding Value
        @AuraEnabled public List recordValue;  //Record
        @AuraEnabled public Id recordId; //Record Id used for Firing Events
    public class TargetTable{
        @AuraEnabled public List<header> headerList; //Header wrapper
        @AuraEnabled public List  records; //actual list of records
        @AuraEnabled public List  ListOfEachRecord; //curated wrapped list of record facilitated for table 

Lightning Component.cmp:

<aura:component controller="DynamicTableClass" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	<aura:attribute name="Table_header_Records" type="object"/> 
    <aura:attribute name="Error" type="boolean" default="false" description="use for displaying error in query or backend exception"/>
    <aura:attribute name="Message" type="boolean" default="false" description="use for display no record found message"/>
    <aura:handler name="init" value="{!this}" action="{!c.getRecordsForTable}"/>
    <aura:attribute name="showHeaders" type="Boolean" default="false"/> 
    <article class="slds-card">
    <aura:if isTrue="{!v.Error}">
               <div class="slds-text-color--error">Error In Query Or Backend Exception, check With it </div>
        <aura:if isTrue="{!v.Message}">
               <div class="slds-text-color--error"> No Result Found...</div>
       <aura:if isTrue="{!v.showHeaders}">
           <div class="slds-center" style="align:center;">
       <div class="slds-table--header-fixed_container" style="height:350px;">
    <div class="slds-scrollable_y" style="height:100%;">
       <table class="slds-table slds-table_bordered slds-table--header-fixed">
           <tr class="slds-text-title--caps">
               <aura:iteration items="{!v.Table_header_Records.headerList}" var="h"> 
               <th scope="col" onclick="{!c.sortColumn}" data-value="{!h.index}">
                  <div class="slds-truncate slds-cell-fixed" title="{!}">{!}
            <aura:if isTrue="{! (h.sorted == 0) }">&nbsp;  ▼ </aura:if>  
            <aura:if isTrue="{! (h.sorted == 1) }"> &nbsp;  ▲ </aura:if>
            <aura:iteration items="{!v.Table_header_Records.ListOfEachRecord}" var="tar">
                    <tr onclick="{!c.displayfields}" data-value="{!tar.recordId}">
                  <aura:iteration items="{!tar.recordValue}" var="value">
                    <a><div class="slds-truncate">{!value}</div></a> 

Lightning Controller.js:

	getRecordsForTable : function(component, event, helper) {
        var action=component.get("c.displayTable");
                               var records = component.get("v.Table_header_Records");
                                   component.set("v.Error", true);
                               if (records!=null && records.ListOfEachRecord.length == 0) {
                                   component.set("v.Message", true);
                               } else {
                                   component.set("v.Message", false);
    sortColumn : function(component, event, helper) {
        var ctarget = event.currentTarget;
        var Fieldindex = ctarget.dataset.value;
        console.log("selected Field" Fieldindex);
        var Wrapedrecords = component.get("v.Table_header_Records");
        var objectRecord = Wrapedrecords.ListOfEachRecord;
        var headerRecord = Wrapedrecords.headerList;
        for(var i=0;i<headerRecord.length;i  ){
            console.log("loop:" headerRecord[i].name " - " Fieldindex);
            {	console.log("match entered");
             var sorted = headerRecord[i].sorted;
                 objectRecord.sort(function(a,b) {
                     return (a['recordValue'][headerRecord[i].index].toString().toLowerCase()  < b['recordValue'][headerRecord[i].index].toString().toLowerCase() ) ? 1 : ((b['recordValue'][headerRecord[i].index].toString().toLowerCase()  < a['recordValue'][headerRecord[i].index].toString().toLowerCase() ) ? -1 : 0);} );
             else if(sorted==0 || sorted==2)
                 objectRecord.sort(function(a,b) {return (a['recordValue'][headerRecord[i].index].toString().toLowerCase()  > b['recordValue'][headerRecord[i].index].toString().toLowerCase() ) ? 1 : ((b['recordValue'][headerRecord[i].index].toString().toLowerCase()  > a['recordValue'][headerRecord[i].index].toString().toLowerCase() ) ? -1 : 0);} ); 

Application :

   <aura:application extends="force:slds">
    <c:testDynamicComponent ></c:testDynamicComponent>
    <c:DynamicTablecomponent ></c:DynamicTablecomponent>

Screen Shot 2018-04-25 at 6.54.28 PM

Clicking on the Column will sort the column:
Screen Shot 2018-04-25 at 6.55.48 PM

Place we need to modify code to make it run on different object

var action=component.get("c.Get_Record_For_Table_Input_From_Query");
        action.setParams({"objectName":"contact","queryFields":"name,title,phone,email","fullQuery":"select name,title,phone,email from contact"});

Or we can call this method DynamicTableClass.Get_Record_For_Table_Input_From_Query(objectName, queryFields, fullQuery) from other apex class.

Similarly we can create Different component that will display records from different object by just modifying the parameter passed to Get_Record_For_Table_Input_From_Query() function.

Screen Shot 2018-04-25 at 7.00.30 PM

Other Features:

  1. On Click of a row, a Controller function will be called , we can get the record id of that row by
var ctarget = event.currentTarget;
var RecordID = ctarget.dataset.value;

we can use the Record Id to fire events or else do something as you wish :D.

2. Sorting Done Client side without extra libraries , so no headache in creating static resource fields. And its fast , no server calls.

3.Scrollable View , so we can see may records at a time , we can adjust the height of table according to your wish.

3 thoughts on “Dynamic Reusable Lightning Table Component

  1. I am working on using this ( this is so good for many things). In your git comments you note to just go to, and change the query. I can’t find this, can you give some more direction on this. Do i have to still copy all the code? ( in a sandbox and then deploy?) change that code then it will work?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s