Skip to main content

Connect #ZOOM with #Salesforce using #Zapier | Salesforce Tutorials

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 😊

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

Post a Comment

Popular posts from this blog

How to send WhatsApp from Lightning Component Salesforce ?

Send WhatsApp from Lightning Component SalesforceHi folks, in this article I will explain how you can send WhatsApp from Lightning Component using https://wa.me/
In this example I will create a Quick Action button on Contact which will be connected with my Lightning Component.
Please follow the steps below : 
Step 1 : Create a Lightning Component & Apex as shown below
WhatsApp.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<aura:componentcontroller="Vlog_whatsappCTRL"implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"access="global"><aura:attributename="recordId"type="String"/><aura:attributename="con"type="Contact"/><aura:attributename="msg"type="String"/><aura:handlername="init"action…

Send WhatsApp and Save Chat using Lightning Component Salesforce | Salesforce Tutorials

Hello folks,
In this article you will learn to send WhatsApp and Save the Chat using Lightning Component Salesforce. 
Prerequisite : 
Create a custom object WhatsApp__c
Create custom fields as shown below : 


Please follow the code below : 

WhatsAppComponent 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<aura:componentcontroller="Vlog_whatsappCTRL"implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"access="global"><aura:attributename="recordId"type="String"/><aura:attributename="con"type="Contact"/><aura:attributename="msg"type="String"/><aura:handlername="init"action="{!c.doInit}"value="{!this}"/><articleclass="slds-card"><divclass="slds-card__header…

Get Parent Id when overriding standard actions with a Lightning Component in salesforce1 app

How to Get Parent Id when overriding standard actions with a Lightning Component in salesforce1 app ?
In this blog I will explain how you can get Parent Id when overriding standard actions with a lightning component.
For example I have changed my Opportunity New button action with a custom Lightning Component. 
Let's create a new account and from the related tab try creating the new Opportunity. Have you noticed any change in URL ?
Let me share the URL with you :  _________________________________________________________________________ https://kapilbatra1-dev-ed.lightning.force.com/lightning/o/Opportunity/new?recordTypeId=0127F000000htlpQAA&additionalParams=accid%3D0017F00002S6g9H%26&inContextOfRef=1.eyJ0eXBlIjoic3RhbmRhcmRfX3JlY29yZFBhZ2UiLCJhdHRyaWJ1dGVzIjp7Im9iamVjdEFwaU5hbWUiOiJBY2NvdW50IiwicmVjb3JkSWQiOiIwMDE3RjAwMDAyUzZnOUhRQVIiLCJhY3Rpb25OYW1lIjoidmlldyJ9LCJzdGF0ZSI6e319&count=3 _________________________________________________________________________
In above URL you …