There are occasions when it becomes necessary to override the default behavior of saving a record in Lightning Data Service (LDS) to implement custom functionality. Let’s explore how to accomplish this.
We can utilize Lightning Data Service (LDS) tags provided by Salesforce for interacting with data, particularly when dealing with a single record.
However, certain scenarios may require overriding the standard functionality to implement custom actions.
Consider this example: if I want to display a form initially with only a few fields and then dynamically populate the remaining fields from the controller file, I can achieve this by overriding the save functionality.
But how can this be achieved?
We need to incorporate the onsubmit={handleSubmit}
attribute in the <lightning-record-edit-form>
tag. This triggers the invocation of the handleSubmit
method in the controller instead of directly saving the record.
Within the handleSubmit
method, we need to halt event propagation, map the remaining fields to their respective values, and finally submit the form.
Allow me to demonstrate with a snippet!
<template> <lightning-record-edit-form object-api-name="Account" onsubmit={handleAccountCreated}> <lightning-messages></lightning-messages> <div class="slds-grid"> <div class="slds-col slds-size_1-of-2"> <lightning-input-field field-name="Name"> </lightning-input-field> </div> </div> <lightning-button type="submit" variant="brand" label="Create Account"></lightning-button> </lightning-record-edit-form> </template>
handleSubmit(event){ // stop the form from submitting event.preventDefault(); //get all the fields const fields = event.detail.fields; //Map remainig fields to values here fields.Industry = 'Apparel'; fields.Rating = 'Hot'; //submit the form this.template.querySelector('lightning-record-edit-form').submit(fields); }
I trust this provided assistance!