Sub topic 2
View, edit and readonly modes
Assume you know LWC templates, event handlers, record IDs, and Salesforce objects. lightning-record-form uses Lightning Data Service (LDS), so Salesforce applies sharing rules, object permissions, and field-level security.
View, edit, and readonly modes
The mode attribute controls the user's interaction:
| Mode | Behavior |
|---|---|
| `view` | Displays fields and provides an Edit action |
| `edit` | Displays editable fields with Save and Cancel |
| `readonly` | Displays fields without an Edit action |
Use view when users usually inspect a record but sometimes change it. Use edit when editing is the main purpose. Use readonly when the component must never offer editing.
<template>
<lightning-record-form
object-api-name="Account"
record-id={recordId}
layout-type="Compact"
mode="view"
columns="2"
onsuccess={handleSuccess}
onerror={handleError}
onsubmit={handleSubmit}
oncancel={handleCancel}>
</lightning-record-form>
</template>The onsubmit handler runs before the save. The onsuccess handler runs after Salesforce saves the record. onerror runs when validation, permissions, or another save operation fails. oncancel runs when the user cancels editing.
import { LightningElement, api } from 'lwc';
export default class AccountForm extends LightningElement {
@api recordId;
handleSubmit(event) {
// event.detail.fields contains the values about to be saved.
console.log('Submitting fields', event.detail.fields);
}
handleSuccess(event) {
console.log('Saved record', event.detail.id);
}
handleError(event) {
console.error(event.detail.message);
}
handleCancel() {
console.log('Edit canceled');
}
}Custom layouts with `lightning-record-edit-form`
Use lightning-record-edit-form when you need to arrange fields yourself, add custom controls, or change submitted values. Without record-id, it creates a new record.
<template>
<lightning-record-edit-form
object-api-name="Contact"
record-id={recordId}
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-output-field field-name="AccountId"></lightning-output-field>
<lightning-button type="submit" label="Save"></lightning-button>
</lightning-record-edit-form>
</template>lightning-input-field renders a Salesforce-aware editor, including picklists and lookup fields. lightning-output-field displays a read-only value. lightning-messages displays field and form validation errors.
Exercise
Which mode should you use when a record must be visible but must not offer an edit action?
Show answer
Use readonly mode.