function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Akanksha Gupta 77Akanksha Gupta 77 

add pagination to dynamic table in lightning component

Hi all, 
I am new to lightning component and I have made a dynamic table which will fetch all the data related to an account but now I have to add pagination to it . Can anyone please help me with the pagination part
This is my code.

controller:

public class DynamicTest{
@AuraEnabled
    public static List<String> listAllObject(){
        List<String> objectList = new List<String>();
        For(Schema.sObjectType sobj: schema.getGlobalDescribe().values()){
            if(sobj.getDescribe().isQueryable())
                objectList.add(sobj.getDescribe().getName()+'####'+sobj.getDescribe().getLabel());
        }
        objectList.sort();
        return objectList;
    }
    @AuraEnabled
    public static DynamicBindingWrapper listAllFields(String objectName){
        DynamicBindingWrapper dynamicData = new DynamicBindingWrapper();
        List<fieldDataWrapper> wrapperList =  new List<fieldDataWrapper>();
        // Create Dynamic Query Start ..
        String theQuery = 'SELECT ';
        SObjectType sObjectName = Schema.getGlobalDescribe().get(objectName);
        Map<String,Schema.SObjectField> mfields = sObjectName.getDescribe().fields.getMap();
        For(Schema.SObjectField field : mfields.values()){
            If(field.getDescribe().isAccessible() && !field.getDescribe().getName().EndsWith('Id')
               && field.getDescribe().getName()!='CreatedDate' && field.getDescribe().getName()!='LastModifiedDate'
               && field.getDescribe().getName()!='LastReferencedDate' && field.getDescribe().getName()!='LastReferencedDate'
               && field.getDescribe().getName()!='LastActivityDate' && field.getDescribe().getName()!='LastViewedDate'
               && field.getDescribe().getName()!='IsDeleted'){
               fieldDataWrapper wrapper = new fieldDataWrapper();
               theQuery += field.getDescribe().getName() + ',' ;
                wrapper.label = field.getDescribe().getLabel();
                wrapper.apiName = field.getDescribe().getName();
                wrapperList.add(wrapper);
           } 
        }
        // Trim last comma
        theQuery = theQuery.subString(0, theQuery.length() - 1);
        // Finalize query string
        theQuery += ' FROM '+objectName;
        // Query End ..
        System.debug('#### theQuery = '+theQuery);
        List<sObject> objectData = Database.Query(theQuery);
        if(objectData!=null && objectData.size()>0)
            dynamicData.sObjectData = objectData;
        else
            dynamicData.sObjectData = new List<sObject>{};
        dynamicData.fieldList = wrapperList;
        System.debug('#### dynamicData '+dynamicData);
        return dynamicData;
    }
    /* Class to store the dynamic data 
     * and list of related fields
     */ 
    public class DynamicBindingWrapper{
        @AuraEnabled
        public List<sObject> sObjectData    { get; set; }
        @AuraEnabled
        public List<fieldDataWrapper> fieldList { get; set; }
    }
    /*
     * Class to store the field information
     */ 
    public class fieldDataWrapper{
        @AuraEnabled
        public String label { get; set; }
        @AuraEnabled
        public String apiName { get; set; }
    }

}


component controller.js
({
     doInit : function(component, event, helper) {
        helper.onInit(component, event, helper);
    },
    doHandleChange : function(component, event, helper) {
        helper.onHandleChange(component, event, helper);
    },
    previousPage : function(component, event, helper)

{

var oppList = component.get("v.accountList");

var end = component.get("v.end");

var start = component.get("v.start");

var pageSize = component.get("v.pageSize");
var paginationList = [];

var counter = 0;

for(var i= start-pageSize; i < start ; i++)

{

if(i > -1)

{

paginationList.push(oppList[i]);

counter ++;

}

else {

start++;

}

}

start = start-counter;

end = end-counter;

component.set("v.start",start);

component.set("v.end",end);

component.set('v.paginationList', paginationList);

},
    nextPage : function(component, event, helper)

{

var oppList = component.get("v.accountList");

var end = component.get("v.end");

var start = component.get("v.start");

var pageSize = component.get("v.pageSize");
var paginationList = [];

var counter = 0;

for(var i=end+1; i<end+pageSize+1; i++)

{

if(oppList.length > end)

{

paginationList.push(oppList[i]);

counter ++ ;

}

}

start = start + counter;

end = end + counter;

component.set("v.start",start);

component.set("v.end",end);

component.set('v.paginationList', paginationList);

},
})


component:

<aura:component implements="flexipage:availableForAllPageTypes" controller="DynamicTest">
    <aura:handler name='init' value='{!this}' action='{!c.doInit}' />
    <aura:attribute name='objectList' type='List' />
    <aura:attribute name="isSending" type="boolean" />
    
<aura:attribute name="pageSize" type="Integer" default="10"/>

<aura:attribute name="totalSize" type="Integer"/>

<aura:attribute name="start" type="Integer" />

<aura:attribute name="end" type="Integer"/>

    <div class="slds-m-around_small">
        <div class="slds-page-header">
            <br/>
        </div><br/>
        <div class="slds-grid slds-wrap">
            <div class="slds-size_1-of-2">
                <div class="slds-box_x-small">
                    <!-- show the list of All the Object -->
                    <lightning:select name="selectObject" label="Select an Object" 
                                      onchange="{!c.doHandleChange}" aura:id='selectObject'>
                        <option value="" text="- None -" />
                        <aura:iteration items='{!v.objectList}' var='obj'>
                            <option value="{!obj.key}" text="{!obj.value}" />
                        </aura:iteration>
                    </lightning:select>
                </div>
            </div>
            <br/>
            <ui:scrollerWrapper class="scrollerSize">
                <div class="slds-size_2-of-2">
                    <div id='sfdctable' aura:id='sfdcDiv'>
                        <!-- division that will show the dynamic content -->
                    </div>
                </div>
            </ui:scrollerWrapper>
             
    <div class="slds">

      <div class="slds-form-element">
       <button class="slds-button slds-button--brand" onclick="{!c.previousPage}" disabled="{!v.page &lt;= 1}">
           Previous
        </button>
       <button class="slds-button slds-button--brand" onclick="{!c.nextPage}" disabled="{!v.page >= v.pages}"> Next</button>
     </div>
    </div>
        </div>
    </div>
</aura:component>

Helper :
({
    onInit : function(component, event, helper) {
        /* Call the Apex class method to fetch the List of all object */
        var action = component.get('c.listAllObject');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === 'SUCCESS' && component.isValid()){
                /* set the value to the attribute of the component */
                var responseValue = response.getReturnValue();
                var lstOptions = [];
                for(var i=0; i < responseValue.length; i++){
                    lstOptions.push({
                        value : responseValue[i].split('####')[1],
                        key : responseValue[i].split('####')[0]
                    });
                }
                lstOptions.sort();
                component.set('v.objectList', lstOptions);
                
            }else{
                var errors = response.getError();
                $A.log(errors);
                if(errors || errors[0].message){
                    console(errors[0].message);
                }
            }
        });
        $A.enqueueAction(action);
    },
    onHandleChange : function(component, event, helper){
        /* Call this method whenever user will select the Obejct
         * and show the Dynamic Content */
        var selObject = component.find('selectObject').get('v.value');
        var action = component.get('c.listAllFields');
        if(selObject!=null && selObject!='' && selObject!=undefined){
            action.setParams({
                "objectName" : selObject  
            });
            action.setCallback(this, function(response){
                var state = response.getState();
                if( state === 'SUCCESS' && component.isValid()){
                    //component.find("dynamicBody").set("v.body
                    component.find('sfdcDiv').set("v.body",[]);
                    var responseValue = response.getReturnValue();
                    var objectValue   = responseValue.sObjectData;
                    var fieldList     = responseValue.fieldList;
                    
                    /* Create Dynamic Table */
                    var sObjectDataTableHeader = [];
                    // Create table Header
                    for (var i=0; i <  fieldList.length; i++) {
                        sObjectDataTableHeader.push(fieldList[i].label);
                    }
                    console.log(sObjectDataTableHeader);
                    //Get the count of columns.
                    var columnCount = sObjectDataTableHeader.length;
                    //Create a HTML Table element.
                    var table = document.createElement("TABLE");
                    //table.border = "1";
                    //Add the header row.
                    var row = table.insertRow(-1);
                    for (var i = 0; i < columnCount; i++) {
                        var headerCell = document.createElement("TH");
                        headerCell.innerHTML = sObjectDataTableHeader[i];
                        headerCell.className='hearderClass';
                        row.appendChild(headerCell);
                    }
                    var dvTable = document.getElementById("sfdctable");
                    dvTable.innerHTML = "";
                    dvTable.appendChild(table);
                    /* Create Dynamic Table End */
                    
                    if(objectValue.length){
                        for(var j=0; j < objectValue.length; j++){
                            // Dynamic table Row
                            row = table.insertRow(-1);
                            // Dynamic Table Row End 
                            for (var i=0; i <  fieldList.length; i++) {
                                // Dynamic table Row
                                var cell = row.insertCell(-1);
                                cell.innerHTML = objectValue[j][fieldList[i].apiName];
                                component.set('v.isSending' , false);
                                
                            }
                        }
                    }else{
                        
                    }
                }else{
                    var errors = response.getError();
                    $A.log('Error Details '+errors);
                    if( errors || errors[0].message){
                        console.log('Error Details '+errors[0].message);
                    }
                }
            });
            $A.enqueueAction(action);
        }else{
            component.set('v.isSending' , false);
        }
    },
})
Best Answer chosen by Akanksha Gupta 77
Ajay K DubediAjay K Dubedi
Hi Akanksha,

I have gone through your question. Below link describes the pagination in a very simple way - 

http://www.infallibletechie.com/2018/03/simple-pagination-example-in-lightning.html 

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com

All Answers

Ajay K DubediAjay K Dubedi
Hi Akanksha,

I have gone through your question. Below link describes the pagination in a very simple way - 

http://www.infallibletechie.com/2018/03/simple-pagination-example-in-lightning.html 

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
This was selected as the best answer
Akanksha Gupta 77Akanksha Gupta 77
Hi Ajay,
Thank you for your reply but I have done this part . But I am not getting how to add it to dynamic table .
So please can you help me with it  or guide me what changes should be done