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
Dhanya NDhanya N 

lightning datatable with checkbox issue in lwc

Hi,

I am trying to implement lightning-datatable with checkbox and pagination. But I am facing problem while navigating from one page to another. 
If I select row2,3, in the first five records and click next it automatically select the row7,8 on the next five records.

Please help me to solve this problem.

Thanks,
Dhanya
 
Ajay K DubediAjay K Dubedi
Hi Dhanya,

This is the lightning data table of opportunity and you can modify it accordingly.

---------Component-------
<aura:component controller="ShowOpportunity1" implements="force:lightningQuickActionWithoutHeader,flexipage:availableForAllPageTypes,force:hasRecordId">
    <aura:attribute name="oppList" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="draftvalues" type="Object"/>
    <aura:attribute name="selectedId" type="List"/>
    <aura:attribute name="strRecId" type="String" />
    
    <aura:handler name="init" value="{!this}" action="{! c.init}"/>
    <div>
        <lightning:overlayLibrary aura:id="overlayLibDemo"/>
        
        <lightning:datatable
                             keyField="Id"
                             aura:id="dtTable"
                             data="{! v.oppList }"
                             columns="{! v.columns }"
                             hideCheckboxColumn="false"
                             showRowNumberColumn="false"
                             draftvalues="{!v.draftvalues}"
                             onsave="{! c.handleSaveEdition }"
                             onrowaction="{! c.showModal}"
                             onrowselection="{! c.getSelectedName }"/>
                <lightning:button class="btndesign" variant="brand" label="IsReviewed" title="Brand action" onclick="{! c.checkedAllReveiwed }" />

    </div><br/>
   
</aura:component>
--------controller-----------
 
({
    init: function (c, e, h) {
        console.log('init');
        
        c.set('v.columns', [
            {label: 'Opportunity Name', fieldName: 'linkOppName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            {label: 'Account Name', fieldName: 'linkAccName', type: 'url', 
             typeAttributes: {label: { fieldName: 'AccountName' }, target: '_blank'}},
            {label: 'Close date', fieldName: 'CloseDate', type: 'date',editable: true},
            {label: 'Amount', fieldName: 'Amount', type: 'currency',editable: true},
            {label: 'Stage Name', fieldName: 'StageName', type: 'PickList'},
            {label: 'IsWon', fieldName: 'IsWon', type: 'boolean'},
            {type: "button", typeAttributes: {
                iconName: 'utility:edit',
                label: 'Edit',
                name: 'selectRecord',
                title: 'selectTitle',
                disabled: false,
                value: 'test', }}
        ]);
        h.fetchData(c, e, h);
    },
    
    handleSaveEdition: function (c, e, h) {
        
        h.handelSaveEditionhelper(c,e,h);
    }, 

   //Get detail you want to select.

    getSelectedName: function (c, e) {
        var selectedRows = e.getParam('selectedRows');
        var ids = [];
        for (var i = 0; i < selectedRows.length; i++){
            ids.push(selectedRows[i].Id);
            console.log("You selected: "+ids);
        }
        c.set("v.selectedId",ids);
        
    },
    checkedAllReveiwed : function(c,e,h){
        var selectedIds = c.get("v.selectedId");
        console.log("allids==>"+selectedIds);
        var action = c.get( "c.updateIsReveiwed" ); 
        console.log("now");
        action.setParams({  
            'selectIds' : selectedIds  
        });  
        action.setCallback( this, function( response ) { 
            var responceR = response.getReturnValue();
            var state = response.getState(); 
            console.log("state::"+state);
            if ( state == "SUCCESS" ) {  
                console.log(responceR);
                alert("IsReviewed updated");
            }  
            
        });  
        $A.enqueueAction( action );  
    },
    showModal : function(component, event, helper) {
        console.log("enter showmodal");
        helper.showModalHelper(component, event, helper);
    }
});


-------helper----------
 
({
    fetchData : function(c,e,h){
        var action = c.get("c.fetchOpportunity");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            var responce = response.getReturnValue();
            console.log("responce"+responce);
            console.log("state"+state);
            if (state === "SUCCESS") {
                responce.forEach(function(record){
                     record.linkOppName = '/'+record.Id;
                });
                for(var i=0;i<responce.length;i++){
                    if(responce[i].AccountId != null){
                        responce[i].AccountName = responce[i].Account.Name;
                            responce[i].linkAccName = '/'+responce[i].AccountId;
                    }
                }
                c.set("v.oppList", response.getReturnValue());
            }
            console.log("response.getReturnValue():"+response.getReturnValue());
        });
        $A.enqueueAction(action);
    },
    
    handelSaveEditionhelper : function( c, e, h ) { 
        try{
            var draftValue =e.getParam('draftValues');
            console.log("draft::=="+(JSON.stringify(draftValue)));
            var action = c.get( "c.updateOpportunity" );  
            action.setParams({  
                'oppObj' : draftValue  
            });  
            action.setCallback( this, function( response ) { 
                var responceR = response.getReturnValue();
                var state = response.getState(); 
                console.log("strate::"+state);
                if ( state == "SUCCESS" ) {  
                    console.log(responceR);
                    alert("Opportunity updated");
                }  
                
            });  
            $A.enqueueAction( action );  
        }catch(err){
            console.log(err.message);
        }
    },
    fireSuccessToast : function(component) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({ 
            'title' : 'Success', 
            'message' : 'Opportunities updated sucessfully.' ,
            'type':'success'
        }); 
        toastEvent.fire(); 
    },
    
    fireFailureToast : function(component) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({ 
            'title' : 'Failed', 
            'message' : 'An error occurred. Please contact your administrator.',
            'type':'error'
        }); 
        toastEvent.fire(); 
    },
    
    fireRefreshEvt : function(component) {
        var refreshEvent = $A.get("e.force:refreshView");
        if(refreshEvent){
            refreshEvent.fire();
        }
    },
    showModalHelper : function(component, event, helper) {
        console.log("enter helper modal")
        var row = event.getParam('row');
        var rowId = row.Id;
        var strOppId = component.get("v.draftvalues");
        console.log('Opportunity Id ====>'+rowId);
        $A.createComponent("c:EditOpportunity", 
                           {strRecordId : rowId},
                           function(result, status) {
                               console.log("status==>"+result);
                               if (status === "SUCCESS") {
                                   console.log("enter modal success");
                                   component.find('overlayLibDemo').showCustomModal({
                                       header: "Opportunity Edit Form",
                                       body: result, 
                                       showCloseButton: true,
                                       cssClass: "mymodal", 
                                   })
                               }                               
                           });
    }
    
    
    
})



-----apex-----------
 
public class ShowOpportunity1 {
    @AuraEnabled
    public static List<Opportunity> fetchOpportunity(){
        Try{
            System.debug('enter the apex class');
            List<Opportunity> opportunityList = New List<Opportunity>();
            opportunityList = [Select Name,
                               Account.Name,
                               Amount,
                               CloseDate,
                               StageName,
                               IsWon
                               From Opportunity
                               Limit 50000
                              ];
            system.debug('list::'+opportunityList);
            
            return opportunityList;
        }Catch(Exception e){
            System.debug('Message:::'+e.getMessage()+'line::'+e.getLineNumber());
        }
        return null;
    }
    @AuraEnabled
    public static List<Opportunity> updateOpportunity(List<Opportunity> oppObj ){
        try{
            system.debug('oppObj::'+oppObj);
            update oppObj;
            return oppObj; 
        }Catch(Exception e){
            System.debug('message::'+e.getMessage()+'line :: '+e.getLineNumber());
        }
        return null;
    }
    @AuraEnabled
    public static List<Opportunity> updateIsReveiwed(List<String> selectIds ){
        try{
            system.debug('all ids::'+selectIds);
            List<Opportunity> oppList = [Select Id,isReveiwed__c From Opportunity where Id IN : selectIds];
            List<Opportunity> newOppList = New List<opportunity>();
            for(Opportunity oppObj : oppList){
                oppObj.isReveiwed__c = True;
                newOppList.add(oppObj);
            }
            update newOppList;
            return newOppList; 
        }Catch(Exception e){
            System.debug('message::'+e.getMessage()+'line :: '+e.getLineNumber());
        }
        return null;
    }
    
    
}

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
 
Dhanya NDhanya N
Thanks Ajay for the response. I am facing problem in lwc and data table with pagination.