Sub topic 12
Choosing the Right Form Component
This chapter assumes you can build a basic Lightning Web Component, bind @api properties, and write event handlers. It also assumes you know how lightning-record-form and lightning-record-edit-form work, as covered in earlier chapters. Here you will learn how to pick among the base form components for a given requirement, and what to watch for when you pick wrong.
The three base form components
Lightning Web Components has three base components for working with a single record. All three use Lightning Data Service (LDS), so they respect sharing, object permissions and field-level security without any Apex.
lightning-record-formis the fastest option. One tag gives you a view, edit or create form. You choose fields withfieldsorlayout-type, and the component draws the buttons and handles the save.lightning-record-edit-formis the custom-layout option. You write the markup withlightning-input-fieldand place each field yourself. You also get control over the submit button, the events and the surrounding content.lightning-record-view-formis the read-only counterpart. You placelightning-output-fieldelements in your own layout. It has no edit capability.
The key difference is who owns the layout and the buttons. With lightning-record-form, the component does. With the other two, you do.
Comparing them side by side
| Need | `lightning-record-form` | `lightning-record-edit-form` | `lightning-record-view-form` |
|---|---|---|---|
| View a record | Yes (`mode="view"`) | Only with `lightning-output-field` inside it | Yes |
| Edit a record | Yes | Yes | No |
| Create a record | Yes (omit `record-id`) | Yes (omit `record-id`) | No |
| Use the page layout | Yes (`layout-type`) | No | No |
| Choose fields by list | Yes (`fields`) | Yes (one element per field) | Yes (one element per field) |
| Custom field order and grouping | No | Yes | Yes |
| Custom buttons and markup between fields | No | Yes | Yes |
| Override submit to change values | Limited | Yes, with `submit(fields)` | Not applicable |
| Amount of code | Least | Moderate | Moderate |
A decision flow
Start with what the user needs to do, then narrow down by how much control you need.
When lightning-record-form is the right choice
Pick lightning-record-form when the form is standard and you want little code. Typical cases:
- A quick create or edit form for an object where the order of fields does not matter much.
- A form that should mirror the page layout. With
layout-type, an admin who changes the layout also changes your form, and you do not redeploy code. - A prototype or an internal tool where speed matters more than polish.
A complete view-mode form needs only a few lines:
<template>
<lightning-record-form
object-api-name="Account"
record-id={recordId}
layout-type="Compact"
columns="2"
mode="view">
</lightning-record-form>
</template>When you list fields yourself, import them from @salesforce/schema instead of typing names as strings. The compiler then checks that the references exist, and Salesforce can track the dependency.
import { LightningElement, api } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class AccountForm extends LightningElement {
@api recordId;
fields = [NAME_FIELD, INDUSTRY_FIELD];
}Limits to remember
lightning-record-form trades control for speed. You cannot reorder the layout within a section, insert your own markup between fields, or style individual fields freely. Its buttons are fixed. If you find yourself wanting to work around the component, it is time to move to lightning-record-edit-form.
When lightning-record-edit-form is the right choice
Pick lightning-record-edit-form when any of the following is true:
- You need a specific field order, grouping into your own sections, or a mix of input and output fields.
- You need your own Save and Cancel buttons, or more than one button.
- You need to read or change field values before they are saved.
- You need to show content between fields, such as help text, a banner or a related list.
- You need to pre-populate or hide a field the user should not change.
Without a record-id, the form creates a record. The submit button saves the values in the input fields.
<template>
<lightning-record-edit-form
object-api-name="Contact"
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>The matching handlers read the new record ID from event.detail.id and show toasts:
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ContactCreate extends LightningElement {
handleSuccess(event) {
const recordId = event.detail.id;
this.dispatchEvent(
new ShowToastEvent({
title: 'Contact created',
message: 'Record ID: ' + recordId,
variant: 'success'
})
);
}
handleError(event) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Save failed',
message: event.detail.message,
variant: 'error'
})
);
}
}Overriding submit
The strongest reason to choose lightning-record-edit-form is the submit override. Bind onsubmit={handleSubmit}, cancel the default save, adjust values and submit them yourself:
handleSubmit(event) {
event.preventDefault();
const fields = event.detail.fields;
fields.LastName = (fields.LastName || '').trim();
this.template
.querySelector('lightning-record-edit-form')
.submit(fields);
}If you call preventDefault() and never call submit(), nothing is saved. This is a common source of "the button does nothing" bugs.
When lightning-record-view-form is the right choice
Use lightning-record-view-form when the data is read-only and you want your own layout. You place lightning-output-field elements and get formatted values, such as links for lookups and currency formatting, without writing any formatting code. If the same screen needs an edit action, consider lightning-record-edit-form with a mix of output and input fields, or switch to lightning-record-form in mode="view", which provides an edit button.
Practical decision criteria
Beyond the feature table, these questions settle most cases.
- Who controls the layout? If admins should control it through page layouts, use
lightning-record-formwithlayout-type. If developers control it, use an edit or view form. - How custom is the save? Any logic around save, such as trimming values, setting defaults or conditional validation, points to
lightning-record-edit-form. - How much code will you maintain? Fewer lines mean fewer bugs. Do not move to a custom form just because it feels more flexible.
- Will requirements grow? Moving from
lightning-record-formtolightning-record-edit-formis a rewrite of the template, not a small change. If you already know you need custom buttons, start with the edit form.
Common mistakes when choosing
- Using
lightning-record-formand then fighting it. If you are adding CSS hacks to move fields, switch components. - Using
lightning-record-edit-formfor a plain read-only display. Use a view form orlightning-record-formin view mode instead. - Combining
fieldsandlayout-type. Use one or the other. Pickfieldsfor an explicit list andlayout-typeto follow the page layout. - Hard-coded field names. Import from
@salesforce/schemawhere you can. A typo in a string shows up at runtime, if at all, as a missing field. - Forgetting
lightning-messages. In an edit form, errors that are not tied to one field have nowhere to appear without it.
Worked scenarios
- Scenario 1: a quick "New Case" form in a utility bar. The fields match the Case page layout, and nobody cares about field order. Use
lightning-record-formwithlayout-type="Full"and norecord-id. - Scenario 2: a Lead capture form that lowercases the email and trims the last name. The values must change before saving. Use
lightning-record-edit-formwith a submit override. - Scenario 3: a read-only Account summary card with a custom grid. Use
lightning-record-view-formwithlightning-output-fieldinside your own grid markup. - Scenario 4: an Opportunity form where some fields are shown only to certain stages. Conditional display needs control over markup, so use
lightning-record-edit-formwithlwc:ifaround the fields.
Exercise
A team needs a Contact edit form where the Email field is converted to lowercase before the record is saved, and a Cancel button sits next to Save. Which component should they use, and which part of its API makes the lowercase change possible?
Show answer
They should use lightning-record-edit-form. It supports custom buttons in the markup, and its submit event lets them call event.preventDefault(), change event.detail.fields.Email (for example with toLowerCase()), and then call submit(fields) on the form. lightning-record-form has fixed buttons and offers no comparable control over values before saving.
Exercise
An admin wants the Opportunity form in your component to change automatically whenever they edit the page layout, with no code change. Which component and attribute should you use?
Show answer
Use lightning-record-form with the layout-type attribute (Compact or Full). The form then follows the page layout. lightning-record-edit-form does not read the page layout, because you list each field in the markup.