0

I am trying to delete a record based on the row selection in data table in LWC. So when a row is selected, the record Id is pushed to the array selectedIdsArray but I am trying to pass it to the Apex method deleteAccount but it doesn't work and always end up in catch block. Can anyone please explain where I am going wrong?

JavaScript:

import { LightningElement, wire, track,api } from "lwc";
import deleteListVi from "@salesforce/apex/DeleteListView.deleteListVi";
import { deleteRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import deleteAccount from "@salesforce/apex/DeleteListView.deleteAccount";

export default class DeleteListView extends LightningElement {
  @track columns = [
    {
      label: "Account Name",
      fieldName: "Name"
    },

    {
      label: "Website",
      fieldName: "Website"
    }
  ];

  @track data;
  @api selectedIdsArray = [];
  @api recordId = [];

  @wire(deleteListVi)
  wireAccount({ error, data }) {
    if (data) {
      this.data = data;
    } else if (data) {
      this.error = error;
    }
  }

  getrowId(event) {
    const selectedRows = this.template.querySelector("lightning-datatable");
    var selected = selectedRows.getSelectedRows();


    for (const element of selected) {
      //console.log("elementid", element.Id);
      this.selectedIdsArray.push(element.Id);
    }
    console.log(this.selectedIdsArray);
  }

  handleClick(event) {

    console.log("selectedEvent " + this.selectedIdsArray);
    const recordId = this.selectedIdsArray;
    console.log('recordId '+ recordId );


    deleteAccount({accountIds: recordId})

      .then(result => {
        this.dispatchEvent(
          new ShowToastEvent({
            title: "Success",
            message: "Account deleted",
            variant: "success"
          })
        );
      })
      .catch(error => {
        this.dispatchEvent(
          new ShowToastEvent({
            title: "Error deleting record",
            message: "Error",
            variant: "error"
          })
        );
      });
  }
}

Apex:

public with sharing class DeleteListView {

    @AuraEnabled(cacheable = true)
    public static List<Account> deleteListVi(){
        return [SELECT Id, Name, Website FROM Account LIMIT 10];

    } 

    @AuraEnabled
    public static void deleteAccount(Id[] accountIds){
        delete [SELECT Id,Name, Website FROM Account where Id IN: accountIds];

    }

}

Edit 1:

enter image description here

Edit 2 - When I select two records, it duplicates the 1st record again and the end result is a total of 3 records. I am confused as to why this is happening.

enter image description here

7
  • What error you are getting in catch block ? as you said records are passing to selectedArray property, It is always good to check the apex log to see if any trigger is causing this delete event.
    – brahma
    Apr 12, 2020 at 11:13
  • @brahmajitammana I have attached an image. Issue is that the recordId is able to fetch the Id of the selected row but the question is whether it is passing to the Apex correctly. I have also deactivated all triggers and related triggers. Apr 12, 2020 at 11:34
  • The LWC and APEX code seems to be fine, but the delete operation may also fail due to referential integrity issues or permission issues. Does the user (that you are logged in as) have any object level permission restrictions for deletion? Also, are there any triggers or restrictions on possible child objects? Note that the delete operation on a parent record will fail if the child record deletion causes exception. Try to catch the exception stack trace in apex code.
    – arut
    Apr 12, 2020 at 11:55
  • @arut I figured out the issue. It couldn't delete as it has some associated contacts and opportunities along with it. It's working when I select an Account with no opportunities and contacts but the issue now is that when I select multiple records it adds twice to the array. I am not sure why this is happening. I have attached the image. Apr 12, 2020 at 11:58
  • 1
    I guess the function getrowId(event) is wired as onrowaction handler. In this code, you are fetching the entire lightning data table and getting all the selected rows every time. Hence, its adding duplicate records. I bet if you selected 3 records, then you will have 6 entries in the array (3 entries for first record selected, 2 entries for second record selected and 1 entry for last record selected). You need to change the code inside this method. BTW, you can just use event.detail.row.Id to get the record ID inside this JS handler function.
    – arut
    Apr 12, 2020 at 12:14

1 Answer 1

2

That is because the selectedRows gives all the selected records in every selection.

Either you need to write a logic to check if array contains the id before push or use map method which creates new array and set all values everytime.

You can try updating your getrowId function to something like this.

getrowId(event) {
   this.selectedIdsArray = event.detail.selectedRows.map((element) => {
       return element.Id;
   });
}
2
  • 1
    this.selectedIdsArray = event.detail.selectedRows.map(element => element.Id ); works, too. No need for a return statement if you drop the function block syntax.
    – sfdcfox
    Apr 12, 2020 at 15:48
  • agree @sfdcfox thanks
    – brahma
    Apr 12, 2020 at 18:14

You must log in to answer this question.

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