4

I am trying to clear the selected rows after a deletion action. The delete actions works perfectly. After the Delete from APEX, it performs a refreshApex() which works fine too.

However, the checked rows that where before deletion are still checked in the same position, but in the remaining records in the list.

I need to achieve a function that allows me to set the selected rows to empty, or to reset this attribute of the data-table.

I have tried using a custom id and using getelementById, but doesn't work. Neither of the other solutions I found for the aura:component. I am using pure LWC.

Before Delete:

Before deleting record

After Deleting

After Deleting

As it is seen in the image it maintains the position of the checked as it was before deleting.

HTML

<template>
    <lightning-card variant="Narrow" class="slds-p-top_x-large">
        <div slot="title" class="slds-grid">
            <div class="slds-col--padded ">
                <h2>
                    <lightning-icon icon-name="standard:delegated_account" size="small">
                    </lightning-icon>
                    &nbsp;Developments
                </h2>
            </div>
            <div class="slds-col-padded">
                <lightning-button name="addDevelopmentBtn" label="Add" onclick={clickAddDevelopment}
                    icon-name="utility:add" alternative-text="Add" title="Add Development">
                </lightning-button>
                <lightning-button data-id="dev-table" name="deleteDevelopmentBtn" label="Delete"
                    onclick={clickDeleteDevelopment} icon-name="utility:delete" alternative-text="Delete"
                    title="Delete Development">
                </lightning-button>
            </div>
        </div>
        <template if:true={developments}>
            <lightning-datatable data={developments} columns={columns} key-field="id" onrowaction={handleRowAction}
                onrowselection={getSelectedRows}>
            </lightning-datatable>
        </template>
    </lightning-card>
</template>

JS

import {
    LightningElement,
    track,
    wire,
    api
} from 'lwc';
import {
    NavigationMixin
} from 'lightning/navigation'
import
getAreaItems
from '@salesforce/apex/areaItemsController.getAreaItems'
import
deleteAreaItems
from '@salesforce/apex/areaItemsController.deleteAreaItems'
import {
    deleteRecord
} from 'lightning/uiRecordApi';
import {
    ShowToastEvent
} from 'lightning/platformShowToastEvent';
import {
    refreshApex
} from '@salesforce/apex';

const actions = [{
        label: 'View Details',
        name: 'show_details'
    },
    {
        label: 'Delete',
        name: 'delete_dev'
    }
]
const columns = [{
        label: 'Development Name',
        fieldName: 'sonn_ait_Development_Name__c'
    }, {
        label: 'Sonneil Reference',
        fieldName: 'sonn_ait_Sonneil_Reference_Development__c'
    },
    {
        label: 'Available Units',
        fieldName: 'sonn_ait_NumOfUnits__c'
    },
    {
        type: 'action',
        typeAttributes: {
            rowActions: actions,
        }
    }
]



export default class areaInterestUnitsList extends NavigationMixin(LightningElement) {

    @api recordId
    @track developments = [];
    @track areas = [];
    selectedRows = [];
    fullAreaItems;
    columns = columns;
    error;



    @wire(getAreaItems, {
        areaId: '$recordId'
    })
    getfullAreaItems(result) {
        this.fullAreaItems = result;
        if (result.data) {
            this.developments = this.getDevelopments(result.data);
            this.areas = result.data;
        } else if (result.error) {
            this.error = result.error;
            console.log(this.error);
        }
    }

    getDevelopments(listOfItems) {

        let devs = [];

        for (let i = 0; i < listOfItems.length; i++) {
            switch (listOfItems[i].sonn_ait_Item_Type__c) {
                case 'Development':
                    devs.push(listOfItems[i]);
                    break;
            }
        }
        return devs;

    }

    getSelectedRows(e) {
        this.selectedRows = e.detail.selectedRows;
        this.template.getElementById("dev-table").getSelectedRows();
    }

    clickAddDevelopment(e) {
        console.log('click add dev');
    }

    async clickDeleteDevelopment(e) {
        let idsToDelete = [];

        this.selectedRows.forEach(element => {
            idsToDelete.push(element.Id);
            console.log(element);
        });

        await this.bulkDeleteItems(idsToDelete);
        this.clearCheckedItems();


    }

    bulkDeleteItems(itemIds) {

        if (itemIds.length == 0) {
            this.showToast('No items to delete', 'Please select items from the list in order to be removed', 'error');
            return;
        }

        deleteAreaItems({
            areaItemsId: itemIds
        }).then(() => {
            this.showToast('Area Items Deleted Succesfully', 'All items deleted succesfully', 'success');
            this.refreshItems();
        }).catch(error => {
            this.showToast('Something went wrong', error.body.message, 'error');
            return;
        });

    }

    clearCheckedItems() {
     // THIS IS THE FUNCTION I NEED TO ACHIEVE
    }

    handleRowAction(event) {
        const actionName = event.detail.action.name;
        const row = event.detail.row;

        switch (actionName) {
            case 'show_details':
                this.navigateToRecordViewPage(row.sonn_ait_development__c)
                break;
            case 'delete_dev':
                deleteRecord(row.Id).then(() => {
                        this.showToast('Area Item Deleted', 'The item has been succesfully removed from the interest area', 'success');
                    })
                    .catch(error => {
                        this.showToast('Something went wrong', error.body.message, 'error');
                        return;
                    }).then(() => {
                        this.refreshItems();
                    });


                break;
            default:
        }
    }

    refreshItems() {
        return refreshApex(this.fullAreaItems); //refreshApex only works on the raw object provided by wire directly
    }

    navigateToRecordViewPage(recordId) {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: recordId,
                actionName: 'view'
            }
        });
    }

    showToast(title, message, variant) {
        const event = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant
        });
        this.dispatchEvent(event);
    }

    deleteAreaItem(recordId) {
        deleteRecord(recordId);

    }

}

Apex just performs a SOQL action of deleting from DDBB.

2 Answers 2

2

EDIT: As you already have an attribute named selectedRows, you need to use a new attribute something else, like setSelectedRows you need to use two different attributes to store the selected rows and to reset the selected.

Create one attribute for the selected rows and assign it to [] an empty array, whenever you want to unselect the selected rows.

<lightning-datatable 
    data={developments}
    columns={columns}
    key-field="id"
    onrowaction={handleRowAction}
    onrowselection={getSelectedRows}
    selected-rows={setSelectedRows}
></lightning-datatable>

You will need a reactive property for this.

selectedRows = [];

...

bulkDeleteItems(itemIds) {
    if (itemIds.length == 0) {
        this.showToast(
            'No items to delete',
            'Please select items from the list in order to be removed',
            'error'
        );
        return;
    }

    deleteAreaItems({
        areaItemsId: itemIds
    }).then(() => {
        this.showToast(
            'Area Items Deleted Succesfully',
            'All items deleted succesfully',
            'success'
        );
        this.refreshItems();
        this.setSelectedRows = []; /// empty selection.
    }).catch(error => {
        this.showToast('Something went wrong', error.body.message, 'error');
        return;
    });
}
4
  • Hi Rahul. Not sure if I'm implementing this right. But if I do this, then the data-table just doesn't let check anything. Whenever you check it remains unchecked. Commented Aug 12, 2020 at 10:51
  • Ohh I see, Its because you are using the same attribute to store the selected rows. I will just update the in answer Commented Aug 12, 2020 at 10:58
  • updated the answer, you can use setSelectedRows instead of selectedRows as you need two separate attributes here. Commented Aug 12, 2020 at 11:04
  • 1
    That was it, thanks a lot. Works perfectly. That was an easy solution I just wasn't able to figure out. Thanks again. Commented Aug 12, 2020 at 11:08
3

You don't actually have to set the selected-rows attribute of the lightning-datatable in the template. You can simply clear its value in JavaScript like this:

this.template.querySelector('lightning-datatable').selectedRows = [];

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .