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
Madhusudan Singh 15Madhusudan Singh 15 

How to use getSelectedRows of lightning datatable

Hi All,

I want to delete selected rows from datatable on a button click. How can I do that? Can anyone share a sample working code.

Madhusudan Singh
Raj VakatiRaj Vakati
Refer this code
public class BookController {
    public static List<Book_Categories__c> getBooksByAllCategories(){
        List<Book_Categories__c> categeroy = [Select  Name,(Select Name, Author_Name__c, Book_Categories__c,Publisher_Id__c from Books__r) from Book_Categories__c];
        return categeroy;
    public static List<Book_Categories__c> getBooksCategories(){
        List<Book_Categories__c> categeroy = [Select  Name,Id from Book_Categories__c];
        return categeroy;
    public static List<Books__c> getBooks(Integer limits , Integer offsets){
        Integer intlimits = integer.valueof(limits);
        Integer intoffsets = integer.valueof(offsets);
        List<Books__c> books = [Select Name,Is_Available__c,CreatedDate,publish_status__c,
                                URL__c ,Author_Name__c, Book_Categories__c,Publisher_Id__c from Books__c Order by Name Limit :intlimits Offset :intoffsets];
        return books;
    public static void setBookStatus(String status , List<Books__c> books){
        System.debug('--books --'+books);
        for(Books__c b :books){
            b.publish_status__c = status ;
        update books;
    public static Integer getTotalCount(){
        AggregateResult results = [select  count(Id) total  from Books__c ];
        Integer total =(Integer)results.get('total') ; 
        return total;
    public static void deleteBooks(String ids ){
        Delete [Select id from Books__c where  id=:ids];
<aura:component controller="BookController" implements="force:appHostable">
    <!-- attributes -->
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="selectedRowsCount" type="Integer" default="0"/>
    <aura:attribute name="selectedRowsDetails" type="Object" />
    <aura:attribute name="selectedRowsList" type="List" />
    <aura:attribute name="maxRowSelection" type="Integer" default="5"/>
    <aura:attribute name="selectedRows" type="List" />
    <!--- enableInfiniteLoading  -->
    <aura:attribute name="enableInfiniteLoading" type="Boolean" default="true"/>
    <aura:attribute name="initialRows" type="Integer" default="30"/>
    <aura:attribute name="rowsToLoad" type="Integer" default="10"/>
    <aura:attribute name="totalNumberOfRows" type="Integer" default="10"/>
    <aura:attribute name="loadMoreStatus" type="String" default="Loading .... "/>
    <aura:attribute name="showRowNumberColumn" type="Boolean" default="false"/>
    <aura:attribute name="rowNumberOffset" type="Integer" default="0"/>
    <aura:attribute name="rowsToAdd" type="Integer" default="10"/>
    <aura:attribute name="currentCount" type="Integer" default="10"/>
    <aura:attribute name="activeFilter" type="string" default="All" description="The currently selected actions filter"/>
    <aura:attribute name="sortedBy" type="String"/>
    <aura:attribute name="sortedDirection" type="String"/>
    <aura:attribute name="defaultSortDirection" type="String"/>
    <!-- handlers-->
    <aura:handler name="init" value="{! this }" action="{! c.doInit }"/>
    <div class="my-custom-background">
        <lightning:button label="Complete"  variant="brand" onclick="{!c.handleSelect}"/>
        <lightning:button label="In Completed"  variant="brand" onclick="{!c.handleSelect}"/>
        <lightning:button label="Pre Order"  variant="brand" onclick="{!c.handleSelect}"/>
    <!-- the container element determine the height of the datatable -->
    <div style="height: 600px">
        <h1> Total Rowns : {! v.totalNumberOfRows}</h1>
        <h1>Selected Rows: {! v.selectedRowsCount }</h1>
        <h1>Selected Objects: {! v.selectedRowsDetails }</h1>
        <h1>Current Offset : {! v.currentCount }</h1>
        <lightning:datatable columns="{! v.columns }"
                             data="{! }"
                             onrowaction="{! c.handleRowAction }"
                             selectedRows="{! v.selectedRows }"
                             maxRowSelection="{! v.maxRowSelection }"
                             onrowselection="{! c.updateSelectedText }"
                             loadMoreOffset="{! v.loadMoreOffset }"
                             onheaderaction="{! c.handleHeaderAction }"
                             sortedBy="{! v.sortedBy }"
                             sortedDirection="{! v.sortedDirection }"
                             defaultSortDirection="{! v.defaultSortDirection }"
                             onsort="{! c.updateColumnSorting }"
                             onloadmore="{! c.loadMoreData }"/>
    {! v.loadMoreStatus }
    doInit : function(component, event, helper) {
        var totalCnt = component.get("c.getTotalCount");
        totalCnt.setCallback(this, function(a) {
            component.set("v.totalNumberOfRows", a.getReturnValue());
        var actions = [
            { label: 'Show details', name: 'show_details' },
            { label: 'Delete', name: 'delete' }
        var headerActions = [
                label: 'All',
                checked: true,
                label: 'Completed',
                checked: false,
                label: 'In Completed',
                checked: false,
                name:'In Completed'
                label: 'Pre Order',
                checked: false,
                name:'Pre Order'
        component.set('v.columns', [
            {label: 'Name', fieldName: 'Name', type: 'text',sortable:true ,actions: headerActions},
            {label: 'URL', fieldName: 'URL__c', type: 'url',sortable:true,actions: headerActions},
            {label: 'Author Name', fieldName: 'Author_Name__c', type: 'text',sortable:true},
            {label: 'publish status', fieldName: 'publish_status__c', type: 'text',sortable:true},
            {label: 'Publisher Id', fieldName: 'Publisher_Id__c', type: 'text',sortable:true,actions: headerActions},
            { type: 'action', typeAttributes: { rowActions: actions } } 
    updateSelectedText : function(component, event, helper){
        var selectedRows = event.getParam('selectedRows');
        //  console.log('selectedRows'+selectedRows);
        component.set("v.selectedRowsCount" ,selectedRows.length );
        let obj =[] ; 
        for (var i = 0; i < selectedRows.length; i++){
        component.set("v.selectedRowsDetails" ,JSON.stringify(obj) );
        component.set("v.selectedRowsList" ,event.getParam('selectedRows') );
    handleSelect: function (component, event, helper) {
        var arr = component.get('');
        var obj =  component.get("v.selectedRowsList");
        console.log('obj '+JSON.stringify(obj) );
        var selectedButtonLabel = event.getSource().get("v.label");
        console.log('Button label: ' + selectedButtonLabel);
        var updateAction = component.get("c.setBookStatus");
        updateAction.setParams({ status : selectedButtonLabel , books: obj});
        updateAction.setCallback(this, function(a) {
    loadMoreData: function (component, event, helper) {
        //Display a spinner to signal that data is being loaded
        event.getSource().set("v.isLoading", true);
        //Display "Loading" when more data is being loaded
        component.set('v.loadMoreStatus', 'Loading');
        helper.fetchData(component, component.get('v.rowsToLoad')).then($A.getCallback(function (data) {
            if (component.get('').length >= component.get('v.totalNumberOfRows')) {
                component.set('v.enableInfiniteLoading', false);
                component.set('v.loadMoreStatus', 'No more data to load');
            } else {
                var currentData = component.get('');
                //Appends new data to the end of the table
                var newData = currentData.concat(data);
                component.set('', newData);
                component.set('v.loadMoreStatus', 'Please wait ');
            event.getSource().set("v.isLoading", false);
    handleRowAction: function (cmp, event, helper) {
        var action = event.getParam('action');
        var row = event.getParam('row');
        switch ( {
            case 'show_details':
                var navEvt = $A.get("e.force:navigateToSObject");
                    "recordId": row.Id,
                    "slideDevName": "detail"
            case 'delete':
                var rows = cmp.get('');
                var rowIndex = rows.indexOf(row);
                console.log('rowIndex row'+rows[rowIndex].Id);
                var deleteAct = cmp.get("c.deleteBooks");
                deleteAct.setParams({ ids : rows[rowIndex].Id });
                var toastEvent = $A.get("e.force:showToast");
                    "title": "Success!",
                    "message": "The record has been delete successfully."
                rows.splice(rowIndex, 1);
                cmp.set('', rows);
    handleHeaderAction: function (cmp, event, helper) {
        // helper.getData(cmp);
        var actionName = event.getParam('action').name;
        var colDef = event.getParam('columnDefinition');
        var columns = cmp.get('v.columns');
        var activeFilter = cmp.get('v.activeFilter');
        if (actionName !== activeFilter) {
            var idx = columns.indexOf(colDef);
            var actions = columns[idx].actions;
            actions.forEach(function (action) {
                action.checked = === actionName;
            cmp.set('v.activeFilter', actionName);
            cmp.set('v.columns', columns);
    // Client-side controller called by the onsort event handler
    updateColumnSorting: function (cmp, event, helper) {
        var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        // assign the latest attribute with the sorted column fieldName and sorted direction
        cmp.set("v.sortedBy", fieldName);
        cmp.set("v.sortedDirection", sortDirection);
        helper.sortData(cmp, fieldName, sortDirection);

Madhusudan Singh 15Madhusudan Singh 15
Thanks Raj, But I am looking for How to use standard function which comes with datatable, 'getSelectedRows' is one of the function which comes with datatable. I am not finding any working example of that.
Kleytman Aular 58Kleytman Aular 58
It may be a little late but others as I did, can came for the same information, 

What I used was,

In the markup side of the component:
<lightning:datatable keyField="id" data="{! v.ResLines }" columns="{! v.ResLineColumns }" aura:id="linesTable"/>
Note de aura:id attribute

In the controller side you can do something like:
let lines = [];
lines = cmp.find('linesTable').getSelectedRows();

So, your find the lightning:datatable by its aura:id and the you can use the method