Record Form onLoad, onSubmit and onSuccess event in Lightning Web Component

Using lightning-record-form we can create complete record Create, Edit or View form with few of line of code, we do not need to worry about writing code to include fields, they will be included automatically based on layout type and layout assigned to the running user.

LWC Record Create Form

Create a new Web Component accountCreateForm

accountCreateForm.html

<template>
  <lightning-card>
    <h3 slot="title">
      <lightning-icon icon-name="standard:account" size="small"></lightning-icon>
      <span class="slds-p-horizontal_small">New Account</span>
    </h3>
    <p class="slds-p-horizontal_small">
      <lightning-record-form object-api-name={accountObject} layout-type="Full" columns="2" onsuccess={handleAccountCreated}
        onsubmit={handleFormSubmitted} onload={handleOnLoad}></lightning-record-form>
    </p></lightning-card>
</template>

Add the following code in the JavaScript controller of the component.

accountCreateForm.js

import {
  LightningElement
} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

/**
 * Creates Account records.
 */
export default class AccountCreator extends LightningElement {

  accountObject = ACCOUNT_OBJECT;

  handleOnLoad(event) {
    console.log(JSON.stringify(event.detail));
  }

  handleFormSubmitted(event) {
    event.preventDefault(); // stop the form from submitting
    const fields = event.detail.fields;
    fields.Description = 'Description updated on Record Submit';
    this.template.querySelector('lightning-record-form').submit(fields);
  }

  handleAccountCreated(event) {
    const updatedRecord = event.detail.id;
    console.log('onsuccess: ', updatedRecord);
  }
}

Documentation: https://developer.salesforce.com/docs/component-library/bundle/lightning-record-form/documentation

Was this post useful? If yes then please share.



Leave a Comment

All fields marked with an asterisk (*) are required


shares