How to reset lightning-record-edit-form and get also get record id in Salesforce?

How to reset lightning-record-edit-form and get also get record id in Salesforce?

Sample Code:

HTML:

<template>
    <lightning-card title="Lead Creation">
        <lightning-record-edit-form object-api-name="Lead" onsubmit={handleSubmit} onsuccess={handleSuccess}>
            <lightning-messages></lightning-messages>
            <lightning-input-field field-name="FirstName"></lightning-input-field>
            <lightning-input-field field-name="LastName"></lightning-input-field>
            <lightning-input-field field-name="Email"></lightning-input-field>
            <lightning-input-field field-name="Phone"></lightning-input-field>
            <lightning-input-field field-name="Company"></lightning-input-field>
            <lightning-button label="Create Lead" variant="brand" type="submit"></lightning-button>&nbsp;&nbsp;&nbsp;  
            <lightning-button label="Reset" variant="brand" onclick={handleReset}></lightning-button>     
        </lightning-record-edit-form>
    </lightning-card>
</template>

JavaScript:

import { LightningElement } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class LeadCreationTab extends LightningElement {

    handleSubmit( event ) {

        event.preventDefault();        
        let fields = event.detail.fields;
        console.log( 'Fields are ' + JSON.stringify( fields ) );
        this.template.querySelector( 'lightning-record-edit-form' ).submit( fields );

    }

    handleReset( event ) {

        const inputFields = this.template.querySelectorAll( 'lightning-input-field' );
        if ( inputFields ) {
            inputFields.forEach( field => {
                field.reset();
            } );
        }

    }

    handleSuccess( event ) {
        
        console.log( 'Record Id is ' + event.detail.id );
        this.dispatchEvent(
            new ShowToastEvent( {
                title: 'Lead Submission Result',
                message: 'Lead Submitted Successfully',
                variant: 'success',
                mode: 'sticky'
            } )
        );

    }

}

meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply