Sub topic 10
Overriding submit to set or validate field values
This chapter assumes you can build a basic lightning-record-edit-form with lightning-input-field components, and that you know how to handle its onsuccess and onerror events. It also assumes you are comfortable with LWC event handlers and this.template.querySelector.
Why override submit
By default, a lightning-record-edit-form saves the values the user entered when they click a button of type="submit". That is enough for many forms. Sometimes you need to act before the save:
- Clean up a value, such as trimming whitespace from a last name.
- Set a field the user does not see, such as a lead source or a default status.
- Run a check that the platform cannot express as a validation rule, and stop the save if it fails.
- Combine values from several inputs into one field.
The form fires a submit event just before it saves. You listen to it with onsubmit={handleSubmit}. Inside the handler you can cancel the default save and call the form's submit() method yourself with the values you want.
What the submit event gives you
The event is a CustomEvent. Its detail property has one member you need, fields. This is a plain object whose keys are field API names and whose values are the current input values.
Two details matter here:
detail.fieldsholds only the fields rendered aslightning-input-fieldcomponents inside the form. A field that has no input in the template is not in the object until you add it.- Calling
event.preventDefault()stops the default save. If you skip it and also callsubmit(fields), you can trigger two saves.
Modifying values before saving
The simplest override changes a value and then submits it. This is the handler from the topic's example.
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
fields.LastName = (fields.LastName || '').trim();
this.template
.querySelector('lightning-record-edit-form')
.submit(fields);
}Walking through it:
event.preventDefault()cancels the default save.event.detail.fieldsis read into a local variable.LastNameis trimmed. The|| ''guards against an empty field, where the value can benullorundefined.submit(fields)on the form element saves the object you pass in.
The matching template wires the handler to the form:
<template>
<lightning-record-edit-form
object-api-name="Contact"
onsubmit={handleSubmit}
onsuccess={handleSuccess}
onerror={handleError}>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>
<lightning-button class="slds-m-top_small" type="submit" label="Save"></lightning-button>
</lightning-record-edit-form>
</template>Setting a value the user cannot edit
You can add a key to fields for a field with no visible input. For example, to stamp every new contact with a lead source:
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
fields.LeadSource = 'Web';
this.template
.querySelector('lightning-record-edit-form')
.submit(fields);
}The user's field-level security still applies. If the running user cannot edit LeadSource, the save fails and the error event fires. Setting a value in code does not bypass permissions.
An alternative that needs no handler is a lightning-input-field with a value attribute, hidden with CSS or the variant attribute. A submit override is easier to read and cannot be accidentally changed by the user.
Validating before saving
Validation in the submit handler follows one pattern: check the values, and if they are bad, show feedback and return without calling submit(). Because you already called preventDefault(), nothing is saved.
import { LightningElement } from 'lwc';
export default class ContactCreateValidated extends LightningElement {
errorMessage = '';
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
const email = (fields.Email || '').trim();
if (!email.endsWith('@example.com')) {
this.errorMessage = 'Email must use the example.com domain.';
return;
}
this.errorMessage = '';
fields.Email = email;
this.template
.querySelector('lightning-record-edit-form')
.submit(fields);
}
}The template shows the message when it is set:
<template>
<lightning-record-edit-form object-api-name="Contact" onsubmit={handleSubmit}>
<lightning-messages></lightning-messages>
<template lwc:if={errorMessage}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>
<lightning-button class="slds-m-top_small" type="submit" label="Save"></lightning-button>
</lightning-record-edit-form>
</template>Where each kind of validation belongs
| Check | Best place | Reason |
|---|---|---|
| Required field, picklist restriction, field length | The field definition and `lightning-input-field` | The component enforces these before submit. |
| Rule that compares fields or depends on data | A validation rule in Salesforce | It runs on every save path, not only your form. |
| Rule specific to this screen | The submit handler | Only this component needs it. |
| Rule that needs the database | Apex or a validation rule | The handler has only the form values. |
Client-side checks improve feedback but are not a security control. Another form, an API call, or a data import can skip your handler. Anything that must always hold belongs on the server as a validation rule or trigger.
Built-in field validation still runs first
When the user clicks the submit button, lightning-input-field components check their own constraints, such as a required field left blank. If a field is invalid, the form does not fire submit, and the component shows its own error. Your handler runs only after those checks pass. You do not need to re-check required fields.
Submitting from a button that is not a submit button
If you use a regular button with onclick, call submit() yourself. You then read the values from the inputs, since there is no submit event to give you detail.fields.
handleSaveClick() {
const fields = {};
this.template
.querySelectorAll('lightning-input-field')
.forEach((input) => {
fields[input.fieldName] = input.value;
});
fields.LeadSource = 'Web';
this.template
.querySelector('lightning-record-edit-form')
.submit(fields);
}This works, but built-in required-field checks are not guaranteed to run this way. Prefer type="submit" and the onsubmit handler when you can.
Common mistakes
- Forgetting
preventDefault(). The form saves the original values, then your handler saves again. You get two saves or a confusing error. - Reading
event.fieldsinstead ofevent.detail.fields.fieldslives underdetail. - Adding a field that does not exist or is not writable. The save fails with an error event. Check the API name, including the
__csuffix on custom fields. - Using a field label as the key. Keys are API names, such as
LastName, not "Last Name". - Querying the form too early.
this.template.querySelectorreturnsnullbefore the component renders. Use it only inside event handlers, not the constructor. - Expecting a returned promise.
submit()does not return the saved record. Useonsuccessto readevent.detail.id.
Combining a submit override with success and error handling
The earlier chapters showed success and error handlers that raise toasts. They work unchanged with an override. This complete component joins them:
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ContactCreate extends LightningElement {
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
fields.LastName = (fields.LastName || '').trim();
this.template
.querySelector('lightning-record-edit-form')
.submit(fields);
}
handleSuccess(event) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Contact created',
message: 'Record ID: ' + event.detail.id,
variant: 'success'
})
);
}
handleError(event) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Save failed',
message: event.detail.message,
variant: 'error'
})
);
}
}Check your understanding
Exercise
A developer writes a submit handler that reads event.detail.fields, sets fields.LeadSource = 'Web', and calls submit(fields) but never calls event.preventDefault(). What is the likely result, and what is the fix?
Show answer
The default save still runs with the original values, and the explicit submit(fields) triggers a second save. The fix is to call event.preventDefault() at the start of the handler so only the save with the modified fields happens.
Exercise
You need to reject an Opportunity whose Amount is over 1,000,000 unless the Description is filled in. The rule must hold for every way a record can be saved. Where should it live, and what could you add in the submit handler?
Show answer
Put the rule in a validation rule on the Opportunity object, because it then applies to the API, imports and other forms. In the submit handler you can add the same check for faster feedback. Call preventDefault(), set an error message and return without calling submit() when the check fails.