Delete any record without apex controller in lwc
We can delete any record using passing record Id to deleteRecord method of uiRecordApi.
1. Import deleteRecord method from uiRecordApi.
[import { deleteRecord } from 'lightning/uiRecordApi';]
2. Call the deleteRecord method passing record id to delete.
[// Pass the record id to deleteRecord methoddeleteRecord(this.recordId);]
Let's see with an example:
DeleteRecordUsingUiRecordApi.html
[<template><lightning-button variant="destructive" label="Delete" onclick={deleteAccount}></lightning-button></template>]
DeleteRecordUsingUiRecordApi.js
[import { LightningElement, api } from 'lwc';import { deleteRecord } from 'lightning/uiRecordApi';import { ShowToastEvent } from 'lightning/platformShowToastEvent';import { NavigationMixin } from 'lightning/navigation';export default class DeleteRecordUsingUiRecordApi extends NavigationMixin (LightningElement) {@api recordId;deleteAccount() {// Pass the record id to deleteRecord methoddeleteRecord(this.recordId).then(() => {this.dispatchEvent(new ShowToastEvent({title: 'Success',message: 'Account has been deleted',variant: 'success'}));// Navigate to a object home pagethis[NavigationMixin.Navigate]({type: 'standard__objectPage',attributes: {objectApiName: 'Account',actionName: 'home',},});}).catch(error => {this.dispatchEvent(new ShowToastEvent({title: 'Error while deleting record',message: error.body.message,variant: 'error'}));});}}]
DeleteRecordUsingUiRecordApi.js-meta.xml
[<?xml version="1.0" encoding="UTF-8"?><LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"><apiVersion>48.0</apiVersion><isExposed>true</isExposed><targets><target>lightning__RecordPage</target></targets></LightningComponentBundle>]
You can also find the above code in SWDC WORLD.
COMMENTS