Thursday, August 8, 2019

Delete Record using Wire Service(uiRecordApi) in Lightning Web Component(lwc)

This post explains how to delete record using wire service(uiRecordApi) in lighting web components(lwc)

import { deleteRecord } from 'lightning/uiRecordApi' From scope module

In this demo, I am deleting account record using uiRecordApi.

Example

deleteRecordInLWC.html
<template>
    <div style="text-align: center;">
        <lightning-card title="Delete Record">
            <lightning-button label="Delete Record" onclick={handleDeleteRecord} variant="brand"></lightning-button>
        </lightning-card>
    </div>
</template>
deleteRecordInLWC.js
import { LightningElement, wire } from 'lwc';
// import uiRecordApi to delete record
import { deleteRecord } from 'lightning/uiRecordApi';

// importing to account record to delete
import getAccount from '@salesforce/apex/LWCExampleController.fetchAccount';

// importing to show to toast messages
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class DeleteRecordInLWC extends LightningElement {
    accRecord;

    // getting account record to delete
    @wire(getAccount)
    objAcc(result) {
        if (result.data) {
            this.accRecord = result.data;
        } 
        else if (result.error) {
            this.accRecord = undefined;
        }
    }
    
    // deleteing account record 
    handleDeleteRecord() {
        // passing account id to delete record
        // recordId is required value
        deleteRecord(this.accRecord.Id)
        .then(result => {
            window.console.log('result ====> '+result);
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: 'Account Deleted Successfully!!',
                variant: 'success'
            }),);
        })
        .catch(error => {
            this.dispatchEvent(new ShowToastEvent({
                title: 'Error!!',
                message: JSON.stringify(error),
                variant: 'error'
            }),);
        })
    }
}
deleteRecordInLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="DeleteRecordInLWC">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
ApexClass
public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static Account fetchAccount() {
        Account objAcc =  [Select Id From Account Limit 1];
        return objAcc;
    }
}
Result



Resource
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.reference_delete_record

No comments:

Post a Comment