Overriding default behavior when a record is saved in LDS within Lightning Web Components

At times we need to override the default behavior when a record is saved in LDS to implement custom functionality. Let's look at how to do it.

We can use LDS tags that salesforce provides to interact with data as far as a single record is concerned.

But there might be a few scenarios where we would have to override the standard functionality and implement some custom functionality.

Let me give you an example, If I were to show a form with only a view fields in the form and then take care of pupulating the remaining fields from the controller file then I can do it by overriding the save functionality.

But how can I do it in the first place?

We need to implement onsubmit={handleSubmit} attribute on the tag <ligthning-record-edit-form>.

That is going to invoke the method handleSubmit method in the controller rather than saving the method straight.

In the method handleSubmit we need to stop the event propagation, map the remaining fields to it's values and finally submit the form.

Let me show you 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>
using onsubmit in the template file to override standard behaviour
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);
}
Overriding the standard functionality in LDS with in a LWC

Hope this was helpful!