Delete Multiple Records Using Checkbox In Lightning Webcomponent
ApexClass
=========
public class AccountDeleteController{
@AuraEnabled(cacheable=true)
public static List<Account> displayAccounts(){
return [select Id,Name from Account];
}
@AuraEnabled
public static List<Account> delAccRecords(List<String> selecRecords){
List<Account> returnlist=new List<Account>();
for(Account acc:[select Id,Name from Account where Id in:selecRecords]){
returnlist.add(acc);
}
if(returnlist.size()>0){
try{
delete returnlist;
}
catch(Exception e){
throw new AuraHandledException(e.getMessage());
}
}
return displayAccounts();
}
}
deleteRecords.html
==================
<template>
<lightning-button label="Delete" onclick={handleDelete}>
</lightning-button>
<lightning-datatable
key-field="Id"
data={accounts.data}
columns={columns}
onrowselection={getSelectedId}
>
</lightning-datatable>
</template>
deleteRecords.js
================
import { LightningElement,wire,api } from 'lwc';
import displayAccounts from '@salesforce/apex/AccountDeleteController.displayAccounts';
import delAccRecords from '@salesforce/apex/AccountDeleteController.delAccRecords';
import { refreshApex } from '@salesforce/apex';
export default class BasicDemo extends LightningElement {
@api columns =[
{ label: 'Name', fieldName: 'Name' }
];
@wire(displayAccounts) accounts;
@api selectedAccountlist=[];
@api errorMessage;
getSelectedId(event){
const selectedRows = event.detail.selectedRows;
console.log('selectedRecordID'+JSON.stringify(selectedRows));
this.selectedAccountlist=[];
for (let i = 0; i<selectedRows.length; i++){
this.selectedAccountlist.push(selectedRows[i].Id);
}
}
handleDelete(){
delAccRecords({selecRecords: this.selectedAccountlist })
.then(()=>{
this.template.querySelector('lightning-datatable').selectedRows=[];
return refreshApex(this.accounts);
})
.catch((error)=>{
this.errorMessage=error;
console.log('unable to delete the record due to'+JSON.stringify(this.errorMessage));
});
}
}
When I remove (cacheable = true) from the displayAccounts method it's not displaying the records. Why is that? could you explain.
ReplyDeleteIf you want to display the data through imperative method then cacheable=true is not required but when it comes to wire property the method should be annotated with(cacheable=true).
ReplyDelete