[SalesForce] How to get unchecked row/checkbox value in lightning:datatable

I am using <lightning:datatable onrowselection="{!c.onSelectContact}" /> for displaying contacts and to check and uncheck checkbox fields.

Then in the component controller i use event.getParam('selectedRows') to get all the selected rows.

Question: How can i find out which particular checkbox has been unchecked because if i use event.getParam('selectedRows') the unchecked row is not part of the selectedRows array.

One way would be to keep a separate list of selected row Ids – but why the overhead? How can i just get the information that certain row/checkbox field is unchecked?

contactList.cmp

<lightning:datatable onrowselection="{!c.onSelectContact}" />

contactListController.js

onSelectContact: function(component, event, helper) {
     var selectedRows= event.getParam('selectedRows');
}

What i want to know is if i select a row i can see it as part of the selectedRows list but if i want to unselect the row event.getParam('selectedRows') does not have the information of the previously selected row. Basically is there a way to get row id during uncheck of a row

Best Answer

Create an attribute of type List as a helper attribute to hold old data -- Try the below code...

yourComponent.cmp - add the attribute

<aura:attribute name="oldData" type="List" default="[]"/>

On your table selection event add this code ---

updateSelectedText: function (component, event) {

    var oldData = component.get("v.oldData");
    var selectedRows = event.getParam('selectedRows');

    if(oldData.length == 0){
        component.set("v.oldData", selectedRows);
    }else if(selectedRows.length < oldData.length){

        var onlyInOld = selectedRows.filter(comparer(oldData));
        var onlyInNew = oldData.filter(comparer(selectedRows));

        //List of all unselected objects from dataTable
        var unselectedData = onlyInOld.concat(onlyInNew);
        console.log("your unselected data", unselectedData);

    }else if(selectedRows.length > oldData.length){
        component.set("v.oldData", selectedRows);
    }

    //helper comparer function
    function comparer(otherArray){
        return function(current){
            return otherArray.filter(function(other){
                return other.Id == current.Id
            }).length == 0;
        }
    }
}

In the javaScript code, you will finally have your list of objects which has been unselected. This line -

var unselectedData = onlyInOld.concat(onlyInNew);

Hope this will help.

Related Topic