[SalesForce] Save & New Button in LWC

I have a requirement to have "Save" and "Save&New". I have a record edit form with two Submit button – "Save" and "Save & New". I found out that on form submission , we will not know which button triggered the submit.

<lightning-record-edit-form object-api-name="Seeded_Acre_Products__c" onsubmit={handleSuccessForm}>
 <div class="slds-grid">
 <div class="slds-col slds-size_1-of-2">
<lightning-input-field field-name="Crop_Product__c"></lightning-input-field> 
<lightning-input-field field-name="Acre__c"></lightning-input-field>
<lightning-input-field field-name="Seeded_Acres__c" value={recordId}></lightning-input-field> 
<lightning-input-field field-name={comments}></lightning-input-field>
</div>
</div>
<lightning-button type="submit" variant="brand" label="Save" ></lightning-button>&nbsp;&nbsp;
<lightning-button  type="submit" variant="brand" label="Save & new" onclick={handleClick} value="saveandnew"></lightning-button>&nbsp;&nbsp;
<lightning-button label="Cancel" onclick={closepopup} ></lightning-button>
</lightning-record-edit-form>

Kindly advise me how to proceed further.

Thanks.

Best Answer

If you have 2 buttons you can create 2 JS methods to handle the buttons separately.

Your first method would simply save, your second method would call your first method and then manufacture the new record.

If you provide some sample code I can try to write a more detailed response. Please note, I wont write you a response that does 100% of the work for you.

Edit:

Based on the provided code sample, I think you need to read this documentation.

Overriding Default Behaviors

To customize the behavior of your form when it loads or when data is submitted, use the onload and onsubmit attributes to specify event handlers. If you capture the submit event and submit the form programmatically, use event.preventDefault() to cancel the default behavior of the event. This prevents a duplicate form submission.

<lightning-record-edit-form object-api-name="Seeded_Acre_Products__c" onsubmit={preventDefaults} > 
<lightning-button type="submit" variant="brand" label="Save" onclick={saveClick}>
</lightning-button>&nbsp;&nbsp; 
<lightning-button type="submit" variant="brand" label="Save & new" onclick={saveAndNewClick} value="saveandnew">
</lightning-button>

Javascript:

preventDefaults(event) {
    event.preventDefault(); 
    this.fields = event.detail.fields;
}

saveClick() {
    this.template.querySelector('lightning-record-edit-form').submit(this.fields);
}

saveAndNewClick() {
    saveClick();
    handleReset();
}

handleReset(event) {
   // Might be possible to use this.fields instead of a selector
   const inputFields = this.template.querySelectorAll(
       'lightning-input-field'
   );
   if (inputFields) {
       inputFields.forEach(field => {
           field.reset();
       });
   }
}
Related Topic