Sub topic 8
Using lightning-input-field, lightning-output-field and lightning-messages
This chapter assumes you can build a basic LWC and that you have seen lightning-record-edit-form wrap a set of fields. Here you will look at the three child components that go inside the form: what each one does, how it relates to Lightning Data Service (LDS), and where it commonly goes wrong.
The role of each child component
lightning-record-edit-form and lightning-record-view-form are containers. They load record data through LDS and share it with the components inside them. The child components render that data.
| Component | Works inside | Purpose |
|---|---|---|
| `lightning-input-field` | `lightning-record-edit-form` | Editable input matched to the field's type |
| `lightning-output-field` | `lightning-record-edit-form`, `lightning-record-view-form` | Read-only display of a field value |
| `lightning-messages` | `lightning-record-edit-form` | Shows save errors and field validation errors |
None of these components works on its own. Outside a form, they have no record context and render nothing useful.
lightning-input-field
You name a field with field-name, and the component picks the right input. A text field gets a text box, a picklist gets a dropdown, a date gets a date picker, and a lookup gets a record search box. You do not choose the input type, and you do not fetch picklist values or labels. The label, help text, and picklist options come from the field's metadata.
LDS also applies the user's permissions. If the user cannot read a field, the input does not appear. If the user can read the field but not edit it, the input is read-only. A missing field in a form is often a field-level security (FLS) issue, not a bug in your template.
Here is a complete component. It edits an existing Account, using imported field references (covered in an earlier chapter).
<template>
<lightning-record-edit-form
object-api-name={accountObject}
record-id={recordId}
onsuccess={handleSuccess}>
<lightning-messages></lightning-messages>
<lightning-input-field field-name={nameField} required></lightning-input-field>
<lightning-input-field field-name={industryField}></lightning-input-field>
<lightning-input-field field-name={phoneField} variant="label-stacked"></lightning-input-field>
<lightning-output-field field-name={createdDateField}></lightning-output-field>
<lightning-button class="slds-m-top_small" type="submit" label="Save"></lightning-button>
</lightning-record-edit-form>
</template>import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import CREATED_DATE_FIELD from '@salesforce/schema/Account.CreatedDate';
export default class AccountEditor extends LightningElement {
@api recordId;
accountObject = ACCOUNT_OBJECT;
nameField = NAME_FIELD;
industryField = INDUSTRY_FIELD;
phoneField = PHONE_FIELD;
createdDateField = CREATED_DATE_FIELD;
handleSuccess() {
this.dispatchEvent(
new ShowToastEvent({
title: 'Account saved',
variant: 'success'
})
);
}
}Common attributes
field-nameis required. It accepts a string such as"Industry"or an imported schema reference.requiredmarks the input as required in the UI. It cannot remove a requirement that the field already has in the schema. Fields that are required in the schema, such asAccount.Name, are always required.disabledmakes the input read-only for the user.variantcontrols the label position. The values arestandard,label-hidden,label-inline, andlabel-stacked.valuesets a value. On a create form it works as a default.nameidentifies the input if you need to tell inputs apart in a shared handler.
Default values on create
Without a record-id, the form creates a record. Use value to prefill a field:
<lightning-record-edit-form object-api-name="Contact">
<lightning-messages></lightning-messages>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="LeadSource" value="Web"></lightning-input-field>
<lightning-button type="submit" label="Create"></lightning-button>
</lightning-record-edit-form>The value you supply must be valid for the field. A picklist value that is not in the picklist, or one that is not allowed for the record type, fails on save.
Reacting to changes
Each input fires a change event. The new value is in event.detail.value. Use it for light logic such as showing a field only when another field has a certain value.
handleIndustryChange(event) {
this.showAdvanced = event.detail.value === 'Technology';
}<lightning-input-field
field-name="Industry"
onchange={handleIndustryChange}>
</lightning-input-field>The shape of event.detail.value depends on the field type. For a lookup it is a record ID or an array of IDs, not a name. Log the event once to confirm what you receive before you build logic on it.
lightning-output-field
An output field displays a value, formatted for its type. It formats dates, currency, and picklist labels as the org would. It turns lookups into links. Use it to show the following:
- values the user cannot edit, such as
CreatedDateor formula fields - context next to inputs, for example an Account name above a Contact form
- read-only views in
lightning-record-view-form
A view form needs a record-id, because there is nothing to view without one:
<template>
<lightning-record-view-form
record-id={recordId}
object-api-name="Account">
<div class="slds-grid">
<div class="slds-col slds-size_1-of-2">
<lightning-output-field field-name="Name"></lightning-output-field>
<lightning-output-field field-name="Industry"></lightning-output-field>
</div>
<div class="slds-col slds-size_1-of-2">
<lightning-output-field field-name="Phone"></lightning-output-field>
<lightning-output-field field-name="OwnerId"></lightning-output-field>
</div>
</div>
</lightning-record-view-form>
</template>Output fields obey FLS the same way inputs do. A field the user cannot read leaves a blank gap, so design layouts that still look right when a field is missing. The variant attribute works as it does on inputs.
An output field only shows what is in the record. It does not compute anything. If you need a derived value, use a formula field on the object, or show the value with your own markup.
lightning-messages
lightning-messages displays errors raised by the enclosing edit form. These include:
- validation rule failures
- required-field errors
- duplicate rule errors
- errors thrown by Apex triggers through
addError - permission and other server-side save errors
Place it once, usually above the fields. With no attributes it needs no JavaScript: when a save fails, the message appears in the form.
You can add onerror as well. The two are not alternatives. lightning-messages gives the user a visible message. The onerror handler lets your code react, for example by logging or showing a toast. Using both is common.
Field-level and form-level errors
A validation rule can attach an error to a specific field or to the whole record. Field-level errors appear on the field. Errors for the whole record, and any that cannot be tied to a field, appear in lightning-messages. If a save appears to do nothing, check whether you have the component in the template before looking elsewhere.
Troubleshooting checklist
- A field is missing from the form. Check FLS for the running user. Then check the spelling of
field-name. A wrong name usually fails without a visible error. - The form saves but the value is unchanged. The field may be read-only for the user, or the
disabledattribute may be set. Calculated fields, such as formula and auto-number fields, cannot be edited. - No error appears on a failed save. Add
lightning-messagesinside the form. - An output field is blank in a view form. Confirm that
record-idis set. In a component placed on a record page,recordIdis only available after the page assigns it. It is not set during construction. - The default
valueis ignored. Make sure the form is a create form. On an existing record, the stored value is loaded, and yourvaluecan conflict with it. - The wrong field name type. If you pass an imported reference, use the reference itself in
field-name={...}, not a string built from it.
Exercise
You build a Contact create form with lightning-record-edit-form. Users click Save when a validation rule fails, and nothing visible happens. Your onerror handler logs to the console. What is the smallest change that shows the failure to the user, and why does it work?
Show answer
Add <lightning-messages></lightning-messages> inside the lightning-record-edit-form, usually above the input fields. The edit form sends save errors, including validation rule failures, to lightning-messages, which renders them. Your onerror handler only runs your own code, so it does not show anything unless you also display a toast or message yourself.
Exercise
You use lightning-output-field for Account.Industry inside a lightning-record-view-form. For one user the field never appears, although other users see it. What is the most likely cause, and where do you check it?
Show answer
The user probably has no read access to the field through field-level security. Check the field's permissions in the user's profile or permission sets. LDS hides fields the user cannot read, so the component renders nothing for them.