Salesforce Asked by Keith C on December 1, 2020
The lightning-record-edit-form has a documented submit
method that I assume can produce similar behavior to a click on a nested submit button. But I can’t find any examples of this.
The documentation describes a fields
argument for the submit
method of:
Submits the form using an array of record fields or field IDs. The
field ID is provisioned from @salesforce/schema/. Invoke this method
only after the load event.
When no argument is supplied to submit
, features like required field validation does not work. I’m not in a position to test right now so am wondering:
submit
argument, does the expected behavior result?lightning-input-field
elements be programmatically obtained? (I note that lightning-record-edit-form
has a field-names
property but that is documented as “Reserved for internal use. Names of the fields to include in the form.”.)I have run into this often since moving from Aura to lightning web components (LWC) and have found that the only solution is to hide a submit button on the form, and then call click on it from your JS method when desired.
A very basic example of this would look like this:
HTML
<template>
<lightning-spinner if:false={rendered}
alternative-text="loading..."
variant="brand"
size="small" >
</lightning-spinner>
<template if:true={rendered}>
<lightning-record-edit-form onsubmit={handleSubmit}
object-api-name="Account" >
<lightning-messages></lightning-messages>
<lightning-input-field field-name="Name" ></lightning-input-field>
<input type="submit" class="hidden" />
</lightning-record-edit-form>
<lightning-button onclick={submitMyformProgramatically}
variant="brand"
label="Click me" >
</lightning-button>
</template>
</template>
JS
import { LightningElement, track} from 'lwc';
export default class App extends LightningElement {
@track
rendered = false;
connectedCallback(){
this.rendered = true;
}
submitMyformProgramatically(){
const btn = this.template.querySelector( ".hidden" );
if( btn ){
btn.click();
}
}
handleFormSubmit( event ){
const fields = event.detail.fields;
console.log( "Fields: ", fields );
}
}
CSS
.hidden {
display: none;
}
in this example, a simple click of the external button will submit this form programatically by locating the button on the form and clicking it.
In Aura lightning:recordEditform
, you used to be able to set an aura:id on the form and simply call submit
from your JS, but that doesn't work in the new LWC lightning-record-edit-form
Correct answer by Ronnie on December 1, 2020
You can call the submit method of the record-edit-form component directly. It is much cleaner than hiding a button.
this.template.querySelector('lightning-record-edit-form').submit();
Answered by CyberJus on December 1, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP