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
venkat bojjavenkat bojja 

Datatable with pagenation concept in lightning component

Hi Team, 

I am having datatable with pagenation concept. As of now i am displaing the records.My requirement is
need to populate the checkbox beside the records what i am getting from the object. And need to sort  records based onReference image colum headers.  At a time we need to check only one check box. After checking that check box i need to click on above any one of the four images iam having 4 images above my datatable and  that should navigate to another component ex: abc.cmp with that checked record Id.Please kindly help me on this.

                                                                                         Thanks in advance...
                            


Controller:


public class ContactAuraController {
    @AuraEnabled
    public static ContactDataTableWrapper getContactData(Decimal pageNumber, Decimal pageSize) {
         
        Integer pSize = (Integer)pageSize;
        Integer pNumber = (Integer)pageNumber;
         
        //Offset for SOQL
        Integer offset = (pNumber - 1) * pSize;
         
        //Total Records
        Integer totalRecords = [SELECT COUNT() FROM Contact];
        Integer recordEnd = pSize * pNumber;
 
        //Instance of Contact DataTable Wrapper Class
        ContactDataTableWrapper objDT =  new ContactDataTableWrapper();  
        objDT.pageSize = pSize;
        objDT.pageNumber = pNumber;
        objDT.recordStart = offset + 1;
        objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
        objDT.totalRecords = totalRecords;
        objDT.contactList = [SELECT Id, Name, Phone, Email FROM Contact ORDER BY Name LIMIT :pSize OFFSET :offset];
        return objDT;
    }
     
    //Wrapper Class For Contact DataTable  
    public class ContactDataTableWrapper {
        @AuraEnabled
        public Integer pageSize {get;set;}
        @AuraEnabled
        public Integer pageNumber {get;set;}
        @AuraEnabled
        public Integer totalRecords {get;set;}
        @AuraEnabled
        public Integer recordStart {get;set;}
        @AuraEnabled
        public Integer recordEnd {get;set;}
        @AuraEnabled
        public List<Contact> contactList {get;set;}
    }
}
=============================================

Component



<!--Pagination.cmp-->
<aura:component controller="ContactAuraController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
     
    <aura:attribute name="ContactList" type="Contact[]"/>
    <aura:attribute name="PageNumber" type="integer" default="1"/>
    <aura:attribute name="TotalPages" type="integer" default="0"/>
    <aura:attribute name="TotalRecords" type="integer" default="0"/>
    <aura:attribute name="RecordStart" type="integer" default="0"/>
    <aura:attribute name="RecordEnd" type="integer" default="0"/>
     
    <div class="slds-m-around_xx-large">
        <h1 class="slds-text-heading--medium">Contacts</h1>
        <br/>
        <div class="slds-float_right">
            <ui:inputSelect aura:id="pageSize" label="Display Records Per Page: " change="{!c.onSelectChange}">
                <ui:inputSelectOption text="10" label="10" value="true"/>
                <ui:inputSelectOption text="15" label="15"/>
                <ui:inputSelectOption text="20" label="20"/>
            </ui:inputSelect>
            <br/>
        </div>
         
        <table class="slds-table slds-table_bordered slds-table_cell-buffer">
            <thead>
                <tr class="slds-text-title_caps">
                    <th scope="col">
                        <strong><div class="slds-truncate" title="Name">Name</div></strong>
                    </th>
                    <th scope="col">
                        <strong><div class="slds-truncate" title="Phone">Phone</div></strong>
                    </th>
                    <th scope="col">
                        <strong><div class="slds-truncate" title="Email">Email</div></strong>
                    </th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.ContactList}" var="con"> 
                    <tr>
                        <th scope="row" data-label="Name">
                            <div class="slds-truncate" title="{!con.Name}">{!con.Name}</div>
                        </th>
                        <th scope="row" data-label="Phone">
                            <div class="slds-truncate" title="{!con.Phone}">{!con.Phone}</div>
                        </th>
                        <th scope="row" data-label="Email">
                            <div class="slds-truncate" title="{!con.Email}">{!con.Email}</div>
                        </th>
                    </tr>
                </aura:iteration> 
            </tbody>
        </table>
         
        <div class="slds-clearfix">
            <div class="slds-page-header" role="banner">
                <div class="slds-float_right">            
                    <lightning:button disabled="{!v.PageNumber == 1}" variant="brand" aura:id="prevPage" label="Prev" onclick="{!c.handlePrev}" />            
                    <lightning:button disabled="{!v.PageNumber == v.TotalPages}" aura:id="nextPage" variant="brand" label="Next" onclick="{!c.handleNext}"/>
                </div>
                <p class="slds-page-header__title">{!v.RecordStart}-{!v.RecordEnd} of {!v.TotalRecords} | Page {!v.PageNumber} of {!v.TotalPages}</p>
            </div>
        </div>
    </div>
</aura:component>
====================================================
Controller.js


({
    doInit: function(component, event, helper) {
        var pageNumber = component.get("v.PageNumber");  
        var pageSize = component.find("pageSize").get("v.value"); 
        helper.getContactList(component, pageNumber, pageSize);
    },
     
    handleNext: function(component, event, helper) {
        var pageNumber = component.get("v.PageNumber");  
        var pageSize = component.find("pageSize").get("v.value");
        pageNumber++;
        helper.getContactList(component, pageNumber, pageSize);
    },
     
    handlePrev: function(component, event, helper) {
        var pageNumber = component.get("v.PageNumber");  
        var pageSize = component.find("pageSize").get("v.value");
        pageNumber--;
        helper.getContactList(component, pageNumber, pageSize);
    },
     
    onSelectChange: function(component, event, helper) {
        var page = 1
        var pageSize = component.find("pageSize").get("v.value");
        helper.getContactList(component, page, pageSize);
    },
})

===============================================================
helper.js

({
    getContactList: function(component, pageNumber, pageSize) {
        var action = component.get("c.getContactData");
        action.setParams({
            "pageNumber": pageNumber,
            "pageSize": pageSize
        });
        action.setCallback(this, function(result) {
            var state = result.getState();
            if (component.isValid() && state === "SUCCESS"){
                var resultData = result.getReturnValue();
                component.set("v.ContactList", resultData.contactList);
                component.set("v.PageNumber", resultData.pageNumber);
                component.set("v.TotalRecords", resultData.totalRecords);
                component.set("v.RecordStart", resultData.recordStart);
                component.set("v.RecordEnd", resultData.recordEnd);
                component.set("v.TotalPages", Math.ceil(resultData.totalRecords / pageSize));
            }
        });
        $A.enqueueAction(action);
    }
})
===================================================================================


Thanks
Venat
 
Best Answer chosen by venkat bojja
MagulanDuraipandianMagulanDuraipandian
Try this Simple Pagination Example in Lightning Component http://www.infallibletechie.com/2018/03/simple-pagination-example-in-lightning.html

All Answers

venkat bojjavenkat bojja
Hi Team,
Please help me on this issue... 

I implemented same component with lightning:dataTable previously implemented with aura:iteration.
Now i am unable to load the records when my page is loaded.Getting error message  
like System.NullPointerException: Attempt to de-reference a null object.What is the cause to get this System.NullPointerException in lightning components.
 and   At a time we need to check only one check box beside the record. After checking that check box i need to click on above any one of the four images iam having 4 images above my datatable and  that should navigate to another component ex: abc.cmp with that checked record Id.Please kindly help me on this.

                                  Thanks in advance...
Thanks
Venkat



MY Code Is 
;
Apex Controller :

public class _PageNationController {

    @AuraEnabled
    public static ContactDataTableWrapper getContactData(Decimal pageNumber, Decimal pageSize) {
         
        Integer pSize = (Integer)pageSize;
        Integer pNumber = (Integer)pageNumber;
         
        //Offset for SOQL
        Integer offset = (pNumber - 1) * pSize;
         
        //Total Records
        Integer totalRecords = [SELECT COUNT() FROM Contact];
        Integer recordEnd = pSize * pNumber;
 
        //Instance of Contact DataTable Wrapper Class
        ContactDataTableWrapper objDT =  new ContactDataTableWrapper();  
        system.debug('objDT------>' + objDT);
        objDT.pageSize = pSize;
        objDT.pageNumber = pNumber;
        objDT.recordStart = offset + 1;
        objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
        objDT.totalRecords = totalRecords;
        objDT.contactList = [SELECT Id,Name,Department,Phone,Email FROM Contact ORDER BY Name LIMIT :pSize OFFSET :offset];
        return objDT;
    }
     
    //Wrapper Class For Contact DataTable  
    public class ContactDataTableWrapper {
        @AuraEnabled
        public Integer pageSize {get;set;}
        @AuraEnabled
        public Integer pageNumber {get;set;}
        @AuraEnabled
        public Integer totalRecords {get;set;}
        @AuraEnabled
        public Integer recordStart {get;set;}
        @AuraEnabled
        public Integer recordEnd {get;set;}
        @AuraEnabled
        public List<Contact> contactList {get;set;}
    }
}
==========================================
Component:

<aura:component controller="LP_PageNationController">


    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <aura:attribute name="ContactList" type="Contact[]"/>
    <aura:attribute name="PageNumber" type="integer" default="1"/>
    <aura:attribute name="TotalPages" type="integer" default="0"/>
    <aura:attribute name="TotalRecords" type="integer" default="0"/>
    <aura:attribute name="RecordStart" type="integer" default="0"/>
    <aura:attribute name="RecordEnd" type="integer" default="0"/>
   
    <aura:attribute name="mycolumns" type="List"/>
  <div class="slds-float_right">
            <ui:inputSelect aura:id="pageSize" label="Display Records Per Page: " change="{!c.onSelectChange}">
                <ui:inputSelectOption text="10" label="10" value="true"/>
                <ui:inputSelectOption text="15" label="15"/>
                <ui:inputSelectOption text="20" label="20"/>
            </ui:inputSelect>
            <br/>
        </div>
        
        
        
        <p class="slds-p-horizontal_small slds-box">
            <lightning:datatable data="{!v.ContactList}" columns="{! v.mycolumns }" keyField="id" onrowselection="{! c.getSelectedName }" onsort="{!c.getsort}" />
        </p>

<div class="slds-clearfix">
            <div class="slds-page-header" role="banner">
                <div class="slds-float_right">            
                    <lightning:button disabled="{!v.PageNumber == 1}" variant="brand" aura:id="prevPage" label="Prev" onclick="{!c.handlePrev}" />            
                    <lightning:button disabled="{!v.PageNumber == v.TotalPages}" aura:id="nextPage" variant="brand" label="Next" onclick="{!c.handleNext}"/>
                </div>
                <p class="slds-page-header__title">{!v.RecordStart}-{!v.RecordEnd} of {!v.TotalRecords} | Page {!v.PageNumber} of {!v.TotalPages}</p>
            </div>
        </div></div>

</aura:component>

                  
        
===============================================================================================================
Controller.js

({
    doInit: function(component, event, helper,pageNumber, pageSize) {
        var pageNumber = component.get("v.PageNumber");  
        var pageSize = component.find("pageSize").get("v.value"); 
        
        
         
    component.set('v.mycolumns', [
                   {label: 'Contact Name', fieldName: 'Name', type: 'Name',sortable:'true'},
               {label: 'Department', fieldName: 'Department', type: 'Text',sortable:'true'},    
                {label: 'Phone', fieldName: 'Phone', type: 'Phone',sortable:'true'},
                {label: 'Email', fieldName: 'Email', type: 'Email',sortable:'true'}
            ]);
        helper.getData(component);
        
    },
     
    handleNext: function(component, event, helper) {
        var pageNumber = component.get("v.PageNumber");  
        var pageSize = component.find("pageSize").get("v.value");
        pageNumber++;
        
        helper.getContactList(component, pageNumber, pageSize);
    },
     
    handlePrev: function(component, event, helper) {
        var pageNumber = component.get("v.PageNumber");  
        var pageSize = component.find("pageSize").get("v.value");
        pageNumber--;
        helper.getContactList(component, pageNumber, pageSize);
    },
     
    onSelectChange: function(component, event, helper) {
        var page = 1
        var pageSize = component.find("pageSize").get("v.value");
        helper.getContactList(component, page, pageSize);
    },
})
===============================================================================================================
helper.js

({
    getData: function(component, pageNumber, pageSize) {
        var action = component.get("c.getContactData");
        action.setParams({
            "pageNumber": pageNumber,
            "pageSize": pageSize
        });
          
        //var action = cmp.get('c.getContacts');
       // var action = cmp.get('c.getRegisteredContacts'); 
        //action.setParams({ search : cmp.get("v.search") });
        action.setCallback(this, (function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set('v.ContactList', response.getReturnValue());
                //cmp.set("v.size",cmp.get("v.mydata1").length);
               // if(cmp.get("v.size")>cmp.get("v.pageSize"))
                 //   cmp.set("v.to",cmp.get("v.pageSize"));
               //else
                   // cmp.set("v.to",cmp.get("v.size"));

               
            }
        }));
        $A.enqueueAction(action);
    },
                  
        

    
})
===============================================================================================================


 
MagulanDuraipandianMagulanDuraipandian
Try this Simple Pagination Example in Lightning Component http://www.infallibletechie.com/2018/03/simple-pagination-example-in-lightning.html
This was selected as the best answer
venkat bojjavenkat bojja
Hi Magulan,
Thanks for your replay,

For pagenation you are provided link is ok,but my main requirement is i need to populate the checkboxes beside the records when my data table is loaded and need to sort the records when i clicked on header labels.I need to check only one check box at a time. I have four images above my table. After i checked my check box i need to click on any one image. Then it navigate to another compoent with checked record's record Id. If i use the auara:Iteration tag at that time i am not able to get the checkboxes but if i use the lightning:datatable tag i can able to get the check boxes. I need to validate that check boxes for check only one at a time. and by clicking on any one of my images it should navigate to another compoent.

 I was taken reference from the URL Link : http://sfdcmonkey.com/2017/01/26/display-record-with-pager-buttons-lightning-component/
But above link aura:iteration is implemented but i changed it in my component as lighting:datatable

So please kindly help me on this.This is very imaportant requirement to me.
                                                           Thanks in advance
Thanks
Venkat.

My Refence code is 

Component:


<aura:component controller="DataTableWithPagenation">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <aura:attribute name="Accounts" type="Account[]"/>
    <aura:attribute name="page" type="integer" description="using for store page Number"/>
    <aura:attribute name="pages" type="integer" description="using for store All Pages page Number"/>
    <aura:attribute name="total" type="integer" description="total records count store "/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <div class="slds-m-around_small">
        <div class="slds-page-header" role="banner">
            
            <p class="slds-page-header__title slds-truncate">{!v.total} Accounts • page {!v.page} / {!v.pages}</p>
            <ui:inputSelect aura:id="recordSize" label="Display Record Per Page: " change="{!c.onSelectChange}">
                <ui:inputSelectOption text="10" label="10" value="true"/>
                <ui:inputSelectOption text="15" label="15"/>
                <ui:inputSelectOption text="20" label="20"/>
            </ui:inputSelect>
        </div>
        
         <p class="slds-p-horizontal_small slds-box">
            <lightning:datatable data="{!v.Accounts}" columns="{! v.mycolumns }" keyField="id"  />
        </p>
        <div class="slds-align_absolute-center">            
                <lightning:button disabled="{!v.page == 1}" variant="brand" label="Previous Page" onclick="{! c.navigate }" />            
                <lightning:button disabled="{!v.page == v.pages}" aura:id="previousPage" variant="brand" label="Next Page" onclick="{! c.navigate }" />
            </div>
        
       <!-- <table class="slds-table slds-table_bordered slds-table_cell-buffer">
            <thead>
                <tr class="slds-text-title_caps">
                    <th scope="col">
                        <div class="slds-truncate" title="Name">Account Name</div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.Accounts}" var="account"> 
                    <tr>
                        <th scope="row" data-label="Opportunity Name">
                            <div class="slds-truncate" title="{!account.Name}">{!account.Name}</div>
                        </th>
                    </tr>
                </aura:iteration>    
            </tbody>
        </table>-->
        
        
        
    </div>
</aura:component>
===============================================================
controller.js

({
   doInit: function(component, event, helper) {
      // this function call on the component load first time     
      // get the page Number if it's not define, take 1 as default
     
      var page = component.get("v.page") || 1;
      // get the select option (drop-down) values.   
      var recordToDisply = component.find("recordSize").get("v.value");
      
       component.set('v.mycolumns', [
                   {label: 'Account Name', fieldName: 'Name', type: 'Name',sortable:'true'},                   
                {label: 'Phone', fieldName: 'Phone', type: 'Phone',sortable:'true'},
                {label: 'Email ID', fieldName: 'Email_ID__c', type: 'Email',sortable:'true'}
            ]);
      
      // call the helper function   
      helper.getAccounts(component, page, recordToDisply);
 
   },
 
   navigate: function(component, event, helper) {
      // this function call on click on the previous page button  
      var page = component.get("v.page") || 1;
      // get the previous button label  
      var direction = event.getSource().get("v.label");
      // get the select option (drop-down) values.  
      var recordToDisply = component.find("recordSize").get("v.value");
      // set the current page,(using ternary operator.)  
      page = direction === "Previous Page" ? (page - 1) : (page + 1);
      // call the helper function
      helper.getAccounts(component, page, recordToDisply);
 
   },
 
   onSelectChange: function(component, event, helper) {
      // this function call on the select opetion change,     
      var page = 1
      var recordToDisply = component.find("recordSize").get("v.value");
      helper.getAccounts(component, page, recordToDisply);
   },
 
})
 
===============================================================================
helper.js


 ({
   getAccounts: function(component, page, recordToDisply) {
 
      // create a server side action. 
      var action = component.get("c.fetchAccount");
      // set the parameters to method 
      action.setParams({
         "pageNumber": page,
         "recordToDisply": recordToDisply
      });
      // set a call back   
      action.setCallback(this, function(a) {
         // store the response return value (wrapper class insatance)  
         var result = a.getReturnValue();
         console.log('result ---->' + JSON.stringify(result));
         // set the component attributes value with wrapper class properties.   
 
         component.set("v.Accounts", result.accounts);
         component.set("v.page", result.page);
         component.set("v.total", result.total);
         component.set("v.pages", Math.ceil(result.total / recordToDisply));
 
      });
      // enqueue the action 
      $A.enqueueAction(action);
   }
})
===================================================
Apex controller:


public   with sharing class DataTableWithPagenation {

   @AuraEnabled
 public static AccountPagerWrapper fetchAccount(Decimal pageNumber ,Integer recordToDisply) {
      Integer pageSize = recordToDisply;
      Integer offset = ((Integer)pageNumber - 1) * pageSize;
    
    // create a instance of wrapper class.
    AccountPagerWrapper obj =  new AccountPagerWrapper();
    // set the pageSize,Page(Number), total records and accounts List(using OFFSET)   
        obj.pageSize = pageSize;
        obj.page = (Integer) pageNumber;
        obj.total = [SELECT count() FROM account];
        obj.accounts = [SELECT Id, Name,Phone,Email_ID__c FROM Account ORDER BY Name LIMIT :recordToDisply OFFSET :offset];
    // return the wrapper class instance .
        return obj;
     }
    
 // create a wrapper class with @AuraEnabled Properties    
 public class AccountPagerWrapper {
    @AuraEnabled public Integer pageSize {get;set;}
    @AuraEnabled public Integer page {get;set;}
    @AuraEnabled public Integer total {get;set;}
    @AuraEnabled public List<Account> accounts {get;set;}
   }
}
=====================================================================================
Refence Image:

User-added image