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
Kartik BhallaKartik Bhalla 

how to keep selected rows(by checkbox) persistent in html table(aura iteration) in pagination using aura component

plz answerrrrrrrr :(
AbhinavAbhinav (Salesforce Developers) 
Your question is not clear.Please elaborate it with some screenshot , code snnipet.
 
mukesh guptamukesh gupta
Hi Kartik,

Please follow below url :-

https://sfdcmonkey.com/2020/12/03/data-table-pagination-checkbox-lightning/

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 

 
Kartik BhallaKartik Bhalla
Hi abhinav, I meant that I have a custom data table(html table) in aura component in which I am doing pagination and I have custom checkbox with every row. now my question is that if I am selecting 2-3 checkboxes on the first page and if i move to the second page and the again go back to the 1st page. then those checkboxes are getting unselected or unchecked. what should i do to make them selected or persistent. plz help 
Kartik BhallaKartik Bhalla
Yes mukesh I have already gone through this but in my code it is not working as expected. Let me share my code

component code:- 

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes,force:hasRecordId" access="global"
                controller="fetchAllContacts">
    
    <!-- Attribute Declration For Pagination -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
    
    <aura:attribute name="contacts" type="Contact[]"/>
    <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="range" type="integer" description="range "/>
    <aura:attribute name="recordEnd" type="Integer"/>
    <aura:attribute name="isSelectAll" type="boolean" default="false"/>
    <aura:attribute name="selectedCount" type="integer" default="0"/>
    <aura:attribute name="pageSize" type="Integer"/>

 <!--TABLE HEADER-->
    
    <lightning:card>
        <thead>    
            <tr class="slds-text-title_caps">
                
                
                
                
                &nbsp;   <th>
                
                <label class="slds-checkbox">
                    <ui:inputCheckbox value="{!v.isSelectAll}" change="{!c.handleSelectAllContact}" aura:id="selectAll"/>
                    <span class="slds-checkbox--faux" />
                    <span class="slds-form-element__label"></span>
                </label>
             
                </th>
              
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<th scope="col">
                <div style="font-size: 15px;">
                    
                    <div class="slds-truncate" title="Name">Contacts</div>
                    
                </div>
                </th>
           
            </tr>

        </thead>  
    </lightning:card>

<!--TABLE-->
    
    <div style="height:575px;">
        <div class="slds-scrollable_y " style="height:100%; width:100%;">
            <table aura:id="table" selectedRows="{!v.selection}" class="slds-table slds-table_fixed-layout">
                
                
                
                <tbody>
                    
                    <aura:iteration items="{!v.contacts}" var="item"> 
                        <tr>
                            <lightning:card variant="Narrow"> 
                                <th>
                                    <label class="slds-checkbox">
                                        <ui:inputCheckbox aura:id="singleCB"  value="{!item.isChecked}" text="{!item.objContact.Id}" change="{!c.checkboxSelect}"  />
                                        <span class="slds-checkbox--faux" />
                                        <span class="slds-form-element__label"></span>
                                    </label>
                                </th>
                                
                                
                                
                                <td>
                                    
                                    <a target="_blank" href="{!'/'+item.objContact.Id}"><div style="height:180px; width:180px;"><aura:unescapedHtml value="{!item.objContact.Profile_Pic__c}" /></div></a>
                                    
                                </td>
                                
                                
                                <th>
                                    <div style="font-size: 17px;">
                                        <div class="slds-truncate" title="{!item.objContact.Name}">
                                            Name: <a href="{!'/'+item.objContact.Id}">{!item.objContact.Name}</a>
                                        </div>
                                        <div class="slds-truncate" title="{!item.objContact.Account.Name}">
                                            Account Name: <a href="{!'/'+item.objContact.AccountId}">{!item.objContact.Account.Name}</a>
                                        </div>
                                        <div class="slds-truncate" title="{!item.objContact.Title}">Title: {!item.objContact.Title}</div>
                                    </div>
                                </th>
                            </lightning:card>    
                        </tr>
                        
                        <!--  <ui:outputRichText value="{!item.Profile_Pic__c}"/>-->
                    </aura:iteration>
                    
                    
                </tbody>
            </table>
        </div>
    </div>
    
    <!--FOOTER-->

<lightning:card>
        
        <aura:set attribute="footer">
            <lightning:layout horizontalAlign="spread"> 
                
                <lightning:layoutItem  >
                    <span class="slds-badge slds-badge_lightest">
                        <p class="slds-truncate">{!v.range}-{!v.recordEnd} of {!v.total} Contacts &nbsp; </p>
                    </span>
                </lightning:layoutItem>
                <lightning:layoutItem  >
                    
                    <div class="slds-p-left_xx-small">
                        
                        <ui:inputSelect aura:id="recordSize" label="Show Records " change="{!c.onSelectChange}">
                            <ui:inputSelectOption text="5" label="5" value="true"/>
                            <ui:inputSelectOption text="10" label="10"/>
                            <ui:inputSelectOption text="20" label="20"/>
                            <ui:inputSelectOption text="50" label="50"/>
                        </ui:inputSelect>
                    </div>
                </lightning:layoutItem>
                
                
                <lightning:layoutItem>
                    <div class="slds-p-right_xx-small">
                        <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>
                </lightning:layoutItem>
                
                
                <lightning:layoutItem  >
                    <span class="slds-badge slds-badge_lightest">
                        <p>Page {!v.page} of {!v.pages}</p></span>
                </lightning:layoutItem>                    
  
                
            </lightning:layout>
        </aura:set>

    </lightning:card> 
        
    <br/>
    
    
     display total record and selected record count    
            <p class="slds-m-around_small">
                <span class="slds-badge slds-badge_lightest" style="display:inline-block">
                    Total Records : {!v.selectedCount > 0 ? v.selectedCount + '/' : ''} {!v.total} 
                </span>
            </p>
    
</aura:component>

js code:-

({
    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
        //console.log('error'+page);
        
        var page = component.get("v.page") || 1;
                console.log('error'+page);

        // get the select option (drop-down) values.   
        var recordToDisply = component.find("recordSize").get("v.value");
                console.log('error'+recordToDisply);

        // call the helper function   
        helper.getContacts(component, page, recordToDisply);
        
    },
    
    //Select all contacts
    handleSelectAllContact: function(component, event, helper) {
        var checkAllList = [];
        var listOfContacts = component.get("v.contacts");
        //var checkvalue = component.find("selectAll").get("v.value"); 
        var selectedHeaderCheck = event.getSource().get("v.value");       
       // var checkContact = component.find("checkContact"); 
        //if(checkvalue == true){
            for(var i=0; i<listOfContacts.length; i++){
                if(selectedHeaderCheck == true){
                    listOfContacts[i].isChecked = true;
                //checkContact[i].set("v.value",true);    
                component.set("v.selectedCount", listOfContacts.length);
            }
            
        else{ 
                listOfContacts[i].isChecked = false;
                //checkContact[i].set("v.value",false);
                component.set("v.selectedCount", 0);  
            }
                checkAllList.push(listOfContacts[i]);
        }
        
        
        component.set("v.contacts", checkAllList);
    },
     
    checkboxSelect: function(component, event, helper) {
       // var selectedCheckList = [];
        //console.log('l'+selectedCheckList);
        //var checkLength = component.find("checkContact");
        var selectedRec = event.getSource().get("v.value");
       // var checkContact = event.getSource().get("v.value");
        //console.log('checkContactlelo'+checkContact);
        var getSelectedNumber = component.get("v.selectedCount");
        console.log('n'+getSelectedNumber);
       
        if(selectedRec == true){
                getSelectedNumber++;
           // selectedCheckList.push(checkContact);
          //  console.log('checkContact'+checkContact.get("v.value"));
        } else {
            getSelectedNumber--;
           // selectedCheckList.pop(checkContact);
            component.find("selectAll").set("v.value", false);
            
        }
     
  
        component.set("v.selectedCount", getSelectedNumber);
        // if all checkboxes are checked then set header checkbox with true   
        if (getSelectedNumber == component.get("v.pageSize")) {
            component.find("selectAll").set("v.value", true);
        }
        
    },

    
    
    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.getContacts(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.getContacts(component, page, recordToDisply);
    },
    
})

helper js:

({
   getContacts: function(component, page, recordToDisply) {
      // create a server side action. 
      
      var action = component.get("c.fetchContact");
      // 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.contacts", result.contacts);
         component.set("v.page", result.page);
         component.set("v.total", result.total);
         component.set("v.pages", Math.ceil(result.total / recordToDisply));
          component.set("v.range", result.range);
          component.set("v.recordEnd", result.recordEnd);
           component.set("v.selectedCount" , 0);
          component.set("v.pageSize", result.pageSize);
         //  component.set("v.isChecked", result.isChecked);
            //component.set("v.isSelectAll", false); 
      });
      // enqueue the action 
      $A.enqueueAction(action);
   }
})

apex class controller:

public with sharing class fetchAllContacts {
    
    @AuraEnabled    
    public static ContactPagerWrapper fetchContact(Decimal pageNumber ,Integer recordToDisply) {
        List<ContactPagerWrapper> modifiedList = new List<ContactPagerWrapper>();
        Integer pageSize = recordToDisply;
        Integer offset = ((Integer)pageNumber - 1) * pageSize;
       // boolean isChecked = true; 
        Integer page = (Integer) pageNumber;
        Integer recordEnd = pageSize * page;
        Integer total = [SELECT count() FROM Contact];
        // create a instance of wrapper class.
        ContactPagerWrapper obj =  new ContactPagerWrapper();
        // set the pageSize,Page(Number), total records and accounts List(using OFFSET)   
        obj.pageSize = pageSize;
        obj.page = page;
        obj.total = total;
        for(Contact c:[SELECT Name,Display_Pic__c,Profile_Pic__c, Account.Name, Title FROM Contact ORDER BY Name LIMIT :recordToDisply OFFSET :offset]){
            modifiedList.add(new ContactPagerWrapper(false,c));
        }
        
        obj.contacts = modifiedList;
        obj.range = offset+1;
        obj.recordEnd = total >= recordEnd ? recordEnd : total;
        //obj.isChecked = isChecked;
        // return the wrapper class instance .
        return obj;
    }
    
    // create a wrapper class with @AuraEnabled Properties    
    public class ContactPagerWrapper {
        //@AuraEnabled public boolean isChecked {get;set;}
        @AuraEnabled public Integer pageSize {get;set;}
        @AuraEnabled public Integer page {get;set;}
        @AuraEnabled public Integer total {get;set;}
        @AuraEnabled public Integer range {get;set;}
        @AuraEnabled public Integer recordEnd {get;set;}
        @AuraEnabled public List<ContactPagerWrapper> contacts {get;set;}
        @AuraEnabled public boolean isChecked {get;set;}
        @AuraEnabled public Contact objContact{get;set;}
        public ContactPagerWrapper(boolean isChecked, Contact objContact){
            this.isChecked = isChecked;
            this.objContact = objContact;
        }
        public ContactPagerWrapper(){
            
        }
        
    }
}


I know the code is very long. but Plzz help me..