How to add Pagination in Lightning Data Table ?


Add Pagination in Lightning Data Table...

Hello folks, please follow below code to add pagination in Lightning Data Table in Lightning Component.

AddPagination.cmp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<aura:component controller="LightningDataTableCTRL" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="recordList" type="List"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="pageNumber" type="Integer" default="1" />
    <aura:attribute name="pageSize" type="Integer" default="10" />
    <aura:attribute name="isLastPage" type="Boolean" default="false" />
    <aura:attribute name="totalPages" type="Integer"/>
    <aura:attribute name="totalRecords" type="Integer"  />
 <aura:attribute name="hasRecords" type="Boolean" default="false" />
    <aura:handler name="init" action="{!c.doInit}" value="{!this}" />
    
    <lightning:layout multipleRows="true" horizontalAlign="center">
        <lightning:layoutItem padding="around-small" size="12">
            <lightning:datatable keyField="id" data="{! v.recordList}"
                                 columns="{! v.columns}"
                                 hideCheckboxColumn="true"
                                 />
        </lightning:layoutItem>
        <aura:if isTrue="{!v.totalPages>1}">
            <lightning:layoutItem padding="around-small" flexibility="auto">
                <lightning:button label="First" iconName="utility:chevronleft" iconPosition="left"
                                  onclick="{!c.onFirst}" disabled="{! v.pageNumber==1}"/>
                <lightning:button label="Prev" iconName="utility:chevronleft" iconPosition="left"
                                  onclick="{!c.onPrev}" disabled="{! v.pageNumber == 1}"/>
                <span class="slds-p-horizontal_small">
                    Page {!v.pageNumber} | Showing records from {!((v.pageNumber-1)*v.pageSize)+1} to {!if(v.totalPages==v.pageNumber, v.totalRecords, (((v.pageNumber-1)*v.pageSize)+v.pageSize))}
                </span>
                <lightning:button label="Next" iconName="utility:chevronright" iconPosition="right" 
                                  disabled="{! v.isLastPage}" onclick="{!c.onNext}"/>
                <lightning:button label="Last" iconName="utility:chevronright" iconPosition="right" 
                                  disabled="{!v.isLastPage}" onclick="{!c.onLast}"/>
            </lightning:layoutItem>
            
        </aura:if>
        
    </lightning:layout>
</aura:component>


AddPaginationController.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
({
    doInit : function(component, event, helper) {
        component.set('v.columns', [
            {label: 'Id', fieldName:'Id',sortable:true,type:'text', initialWidth: 300},
            {label: 'Name', fieldName:'Name',sortable:true,type:'text', initialWidth: 400},
            {label: 'Phone', fieldName:'Phone',sortable:true,type:'text', initialWidth: 300},
            {label: 'Created Date', fieldName:'CreatedDate',sortable:true,type:'text', initialWidth: 400}
        ]);
        helper.getAccounts(component, helper);
        helper.getAccountsCount(component, helper);
    },
   
    onFirst: function(component, event, helper) {
        var totalPages = component.get("v.totalPages");
        component.set("v.isLastPage", false);
        component.set("v.pageNumber", 1);
        helper.getAccounts(component, helper);     
    },
    onPrev: function(component, event, helper) {
        var pageNumber = component.get("v.pageNumber");
        var totalPages = component.get("v.totalPages");
        if(pageNumber <= totalPages){
            component.set("v.isLastPage", false);
            component.set("v.pageNumber", pageNumber-1);
            helper.getAccounts(component, helper);     
        } 
    },
    onNext: function(component, event, helper) {
        var pageNumber = component.get("v.pageNumber");
        var totalPages = component.get("v.totalPages");
        if(totalPages > pageNumber){
            component.set("v.pageNumber", pageNumber+1);
            helper.getAccounts(component, helper);
            if(pageNumber==(totalPages-1)){
                component.set("v.isLastPage", true); 
            }
        }
    },
    onLast: function(component, event, helper) {
        var lastPage = component.get("v.totalPages");
        component.set("v.isLastPage", true); 
        component.set("v.pageNumber", lastPage);
        helper.getAccounts(component, helper);
    },
    
})


AddPaginationHelper.js


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
({
    getAccounts : function(component, helper) {
        var action = component.get("c.getAccountList");
         action.setParams({
            "pageSize" : component.get("v.pageSize").toString(),
            "pageNumber" : component.get("v.pageNumber").toString()
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            var data;
            if(state === 'SUCCESS'){
                var result = response.getReturnValue();
                component.set("v.recordList", result);
            }
        });
        $A.enqueueAction(action);
    },
    getAccountsCount: function(component, helper) {
        const action = component.get("c.getAccountCount");
        // Register the callback function
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
                var result = response.getReturnValue();
                var pageSize=component.get("v.pageSize");
                component.set("v.totalRecords", result)
                var totalPages = Math.ceil(result/pageSize);
                component.set("v.totalPages",totalPages);
            }
        });
        $A.enqueueAction(action);
    },
    
})


LightningDataTableCTRL.apxc



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class LightningDataTableCTRL {
    @AuraEnabled
    public static list<Account> getAccountList(String pageSize, String pageNumber){
        String soql = 'Select Id, Name, Phone, CreatedDate From Account Order By CreatedDate';
        if(pageSize==null){
            pageSize='10';
        }
        if(pageNumber==null){
            pageNumber='1';
        }
        Integer ps = Integer.valueOf(pageSize);
        Integer pn = Integer.valueOf(pageNumber)-1;
        soql += ' limit '+ps+' OFFSET '+(ps*pn);
        
        List<Account> accList= Database.Query(soql);
        if(accList != null && accList.size()>0){
  return accList;
        }
        else{return null;}
    }
     @AuraEnabled
    public static Integer getAccountCount(){
        String soqlStr = 'Select COUNT() From Account';
        Integer recCount= database.countQuery(soqlStr);
        return recCount;
    }
}


Final Output





Please check below links also and subscribe if you like the content : 

If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 😊

Post a Comment

4 Comments

  1. Hi is this free Blog to learn Salesforce

    ReplyDelete
  2. how many records we can display using pagination in lightning ?? like in VF we can display 1000 records only

    ReplyDelete
    Replies
    1. Are you asking the records limit in one page or overall ?

      Delete