LWC Forms and the UI API: record forms, validation, createRecord and picklists
Build Lightning web component forms with lightning-record-edit-form, the UI API adapters, custom validation and Jest tests, with the setup each approach needs.

On this page
Almost every Salesforce screen is a form: create a record, edit it, validate it, show errors. Lightning Web Components give you three layers for this, from ready-made forms to full control through the UI API. Choosing the right layer saves a lot of code.
The business scenario
Juniper Consulting’s service team creates Cases from a custom “Quick Case” panel on the Account page. They want the Account to be prefilled, the Priority picklist to show only valid values, a subject of at least 10 characters, a rule that “High” priority cases need a description, a toast on success, and a clean error message when Salesforce rejects the save. A stock page layout cannot enforce the description rule in the panel the way the team wants, so you will build the form yourself.
Before you start: setup
In Salesforce
- Use a Developer Edition org or sandbox with the Salesforce CLI and VS Code Salesforce extensions; connect with
sf org login web --alias dev. - Create a Salesforce DX project and set
"sourceApiVersion": "68.0". - In Object Manager, Case, confirm the Priority picklist has values (Low, Medium, High) and that Subject and Description are visible to your profile. Check field-level security: the form shows only fields the user can see.
- Optionally create a validation rule on Case:
AND(ISPICKVAL(Priority,"High"), ISBLANK(Description))with the message “High priority cases need a description.” Client checks improve the experience, but server rules remain the real enforcement. - Give your users a permission set with Create on Case and Read on Account.
- For tests, install Jest tooling:
npm installin the project, which includes@salesforce/sfdx-lwc-jestwhen the project was generated by the CLI. Run withnpm run test:unit. - Add the component to the Account record page in Lightning App Builder (the meta file below exposes it).
In the external system
None. If the form should also create a record in an external system, do that in an Apex action called after the save, through a Named Credential, and never from the browser.
How it works
Three layers:
lightning-record-form: one tag, whole form. Quickest, least control.lightning-record-edit-formwithlightning-input-field: you control layout and buttons; Salesforce provides field rendering, picklists, required indicators, field-level security and server errors.- UI API adapters (
createRecord,updateRecord,getObjectInfo,getPicklistValues,getRecordfromlightning/uiRecordApiandlightning/uiObjectInfoApi): full control. You render inputs yourself and call the adapters to save.
The deciding questions: do you need a custom layout or only standard fields? Layer 2. Do you need to compute values, validate across fields or use lightning-input for custom controls? Layer 3.
Validation has two sides. Client checks use the browser, setCustomValidity and reportValidity() on lightning-input. They give instant feedback. Server checks (validation rules, triggers, required fields) always run, and their messages arrive as errors you must display.
Basic example
Layer 2, standard fields, almost no JavaScript.
<template>
<lightning-record-edit-form
object-api-name="Case"
onsuccess={handleSuccess}
onerror={handleError}>
<lightning-messages></lightning-messages>
<lightning-input-field field-name="AccountId" value={recordId}></lightning-input-field>
<lightning-input-field field-name="Subject"></lightning-input-field>
<lightning-input-field field-name="Priority"></lightning-input-field>
<lightning-input-field field-name="Description"></lightning-input-field>
<lightning-button type="submit" label="Create case" variant="brand"></lightning-button>
</lightning-record-edit-form>
</template>import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class QuickCaseBasic extends LightningElement {
@api recordId;
handleSuccess(event) {
this.dispatchEvent(new ShowToastEvent({
title: 'Case created',
message: 'Case ' + event.detail.id + ' was saved.',
variant: 'success'
}));
}
handleError(event) {
console.error(JSON.stringify(event.detail));
}
}lightning-messages shows server errors automatically, including validation rule messages. This is already good enough for many cases.
Advanced end-to-end example
Layer 3, with a validation module that is easy to test, picklist values loaded from the schema, and a clean error path.
force-app/main/default/lwc/quickCase/caseRules.js
export const MIN_SUBJECT_LENGTH = 10;
// Returns an object of { fieldName: message }. Empty object means valid.
export function validateCase(values) {
const errors = {};
const subject = (values.subject || '').trim();
if (subject.length < MIN_SUBJECT_LENGTH) {
errors.subject = `Subject needs at least ${MIN_SUBJECT_LENGTH} characters.`;
}
if (!values.priority) {
errors.priority = 'Choose a priority.';
}
if (values.priority === 'High' && !(values.description || '').trim()) {
errors.description = 'High priority cases need a description.';
}
return errors;
}
// Turns UI API / Apex errors into one readable string.
export function readError(error) {
if (!error) {
return 'Unknown error';
}
const body = error.body;
if (Array.isArray(body)) {
return body.map(e => e.message).join(', ');
}
if (body && body.output && Array.isArray(body.output.errors) && body.output.errors.length > 0) {
return body.output.errors.map(e => e.message).join(', ');
}
if (body && typeof body.message === 'string') {
return body.message;
}
return typeof error.message === 'string' ? error.message : 'Unknown error';
}force-app/main/default/lwc/quickCase/quickCase.js
import { LightningElement, api, wire } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { getObjectInfo, getPicklistValues } from 'lightning/uiObjectInfoApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CASE_OBJECT from '@salesforce/schema/Case';
import PRIORITY_FIELD from '@salesforce/schema/Case.Priority';
import { validateCase, readError } from './caseRules';
export default class QuickCase extends LightningElement {
@api recordId; // the Account Id when placed on an Account page
values = { subject: '', priority: '', description: '' };
errors = {};
saving = false;
serverError = '';
priorityOptions = [];
@wire(getObjectInfo, { objectApiName: CASE_OBJECT })
objectInfo;
@wire(getPicklistValues, {
recordTypeId: '$defaultRecordTypeId',
fieldApiName: PRIORITY_FIELD
})
wiredPriority({ data }) {
if (data) {
this.priorityOptions = data.values.map(v => ({ label: v.label, value: v.value }));
}
}
get defaultRecordTypeId() {
return this.objectInfo?.data?.defaultRecordTypeId;
}
get subjectError() { return this.errors.subject; }
get priorityError() { return this.errors.priority; }
get descriptionError() { return this.errors.description; }
get disableSave() { return this.saving; }
handleChange(event) {
const field = event.target.name;
this.values = { ...this.values, [field]: event.detail.value };
// Clear the message for a field once the user edits it.
if (this.errors[field]) {
this.errors = { ...this.errors, [field]: undefined };
}
}
async handleSave() {
this.serverError = '';
this.errors = validateCase(this.values);
if (Object.keys(this.errors).length > 0) {
return;
}
this.saving = true;
try {
const record = await createRecord({
apiName: CASE_OBJECT.objectApiName,
fields: {
AccountId: this.recordId,
Subject: this.values.subject.trim(),
Priority: this.values.priority,
Description: this.values.description
}
});
this.dispatchEvent(new ShowToastEvent({
title: 'Case created',
message: 'Case ' + record.id + ' was saved.',
variant: 'success'
}));
this.reset();
this.dispatchEvent(new CustomEvent('saved', { detail: { id: record.id } }));
} catch (error) {
// Validation rules and triggers on the server end up here.
this.serverError = readError(error);
} finally {
this.saving = false;
}
}
reset() {
this.values = { subject: '', priority: '', description: '' };
this.errors = {};
}
}force-app/main/default/lwc/quickCase/quickCase.html
<template>
<lightning-card title="Quick case" icon-name="standard:case">
<div class="slds-var-p-around_medium">
<template lwc:if={serverError}>
<div class="slds-text-color_error" role="alert">{serverError}</div>
</template>
<lightning-input
name="subject"
label="Subject"
value={values.subject}
message-when-value-missing={subjectError}
onchange={handleChange}>
</lightning-input>
<div class="slds-text-color_error">{subjectError}</div>
<lightning-combobox
name="priority"
label="Priority"
value={values.priority}
options={priorityOptions}
onchange={handleChange}>
</lightning-combobox>
<div class="slds-text-color_error">{priorityError}</div>
<lightning-textarea
name="description"
label="Description"
value={values.description}
onchange={handleChange}>
</lightning-textarea>
<div class="slds-text-color_error">{descriptionError}</div>
<lightning-button
class="slds-var-m-top_small"
variant="brand"
label="Create case"
disabled={disableSave}
onclick={handleSave}>
</lightning-button>
</div>
</lightning-card>
</template>force-app/main/default/lwc/quickCase/quickCase.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>68.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>force-app/main/default/lwc/quickCase/tests/caseRules.test.js
import { validateCase, readError, MIN_SUBJECT_LENGTH } from '../caseRules';
describe('validateCase', () => {
const good = { subject: 'Printer will not start', priority: 'Low', description: '' };
it('accepts a valid low priority case', () => {
expect(validateCase(good)).toEqual({});
});
it('requires a long enough subject', () => {
const errors = validateCase({ ...good, subject: 'short' });
expect(errors.subject).toContain(String(MIN_SUBJECT_LENGTH));
});
it('ignores surrounding spaces when counting', () => {
expect(validateCase({ ...good, subject: ' abc ' }).subject).toBeDefined();
});
it('requires a priority', () => {
expect(validateCase({ ...good, priority: '' }).priority).toBeDefined();
});
it('requires a description only for high priority', () => {
expect(validateCase({ ...good, priority: 'High' }).description).toBeDefined();
expect(validateCase({ ...good, priority: 'High', description: 'Details' })).toEqual({});
});
});
describe('readError', () => {
it('reads a UI API error array', () => {
expect(readError({ body: [{ message: 'A' }, { message: 'B' }] })).toBe('A, B');
});
it('reads the output.errors form', () => {
const error = { body: { output: { errors: [{ message: 'High priority cases need a description.' }] } } };
expect(readError(error)).toBe('High priority cases need a description.');
});
it('falls back to message and then to a default', () => {
expect(readError({ body: { message: 'Boom' } })).toBe('Boom');
expect(readError({ message: 'Plain' })).toBe('Plain');
expect(readError(null)).toBe('Unknown error');
});
});force-app/main/default/lwc/quickCase/tests/quickCase.test.js
import { createElement } from 'lwc';
import QuickCase from 'c/quickCase';
import { createRecord } from 'lightning/uiRecordApi';
jest.mock('lightning/uiRecordApi', () => ({ createRecord: jest.fn() }), { virtual: true });
const flush = () => Promise.resolve();
function mount() {
const element = createElement('c-quick-case', { is: QuickCase });
element.recordId = '001000000000001AAA';
document.body.appendChild(element);
return element;
}
function fill(element, name, value) {
const field = element.shadowRoot.querySelector(`[name="${name}"]`);
field.dispatchEvent(new CustomEvent('change', { detail: { value } }));
}
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
describe('c-quick-case', () => {
it('shows validation messages and does not save an invalid form', async () => {
const element = mount();
element.shadowRoot.querySelector('lightning-button').click();
await flush();
expect(createRecord).not.toHaveBeenCalled();
expect(element.shadowRoot.textContent).toContain('Subject needs at least 10 characters.');
});
it('saves a valid form with the account id', async () => {
createRecord.mockResolvedValue({ id: '500000000000001AAA' });
const element = mount();
fill(element, 'subject', 'Printer will not start');
fill(element, 'priority', 'Low');
await flush();
element.shadowRoot.querySelector('lightning-button').click();
await flush();
expect(createRecord).toHaveBeenCalledTimes(1);
expect(createRecord.mock.calls[0][0].fields.AccountId).toBe('001000000000001AAA');
});
it('shows a server error such as a validation rule message', async () => {
createRecord.mockRejectedValue({ body: [{ message: 'High priority cases need a description.' }] });
const element = mount();
fill(element, 'subject', 'Printer will not start');
fill(element, 'priority', 'Low');
await flush();
element.shadowRoot.querySelector('lightning-button').click();
await flush();
await flush();
expect(element.shadowRoot.querySelector('[role="alert"]').textContent)
.toContain('High priority cases need a description.');
});
});Run:
sf project deploy start --source-dir force-app --target-org dev
npm run test:unitWhat happens behind the scenes
lightning-record-edit-form and lightning-input-field call the UI API for you. The UI API returns the object’s metadata (field types, labels, picklist values, required flags, field-level security) together with record data, so the form shows only fields the user may see and renders the correct control for each type. When the user presses the submit button, the form posts the values to the UI API and the platform runs the full save: required checks, validation rules, triggers and sharing. If it fails, the error comes back in the response and lightning-messages displays it.
In layer 3 you take over the same conversation. getObjectInfo fetches the object’s metadata, including its default record type id, and getPicklistValues needs that record type id to know which picklist values are valid. That is why getPicklistValues waits for $defaultRecordTypeId: the $ prefix makes the adapter reactive, and it runs only when the value is defined. createRecord sends a UI API request and resolves with the new record’s id.
The adapters share a client-side cache (Lightning Data Service). A second component asking for the same object info does not trigger a second network call, and a record updated through updateRecord refreshes every component that displays it.
The component’s JavaScript decides when to ask the server. Client checks in validateCase run first and cost nothing; only a form that passes them is sent. The server then checks again, because client checks can be bypassed. Errors from the server may arrive in several shapes (an array, body.output.errors, or body.message), which is why readError handles all three.
Test it and verify
- Run
npm run test:unitand confirm all tests pass. - Deploy, add the component to an Account page, and click Create case with an empty form; confirm each message appears.
- Choose High priority, give a subject and leave the description empty; confirm the client rule appears. Remove the client rule temporarily and confirm the server validation rule message appears instead.
- Log in as a user without Create on Case and confirm that the error is readable.
- Open the browser’s Network tab and confirm that picklist values load once.
Common mistakes and fixes
- Relying on client validation only. Server rules still apply; show their messages.
- Using
getPicklistValueswithout a record type id. Wait forgetObjectInfo. - Mutating
this.valuesin place. Create a new object so the template updates. - Not handling the
catch. A rejected promise should show a message, not a console error. - Forgetting
lightning-messages. Edit-form errors vanish without it. - Hardcoding picklist values. They go out of date; load them.
- Missing permissions. If a field is blank or absent, check field-level security.
Key takeaways
- Start with the highest layer that meets the need: record form, then edit form, then adapters.
- Client checks improve experience; the server always has the last word.
- Reactive wires with
$wait for their inputs. - Keep rules in plain modules so they are easy to test.
- Test the invalid, valid and server-error paths.
Where to go next
- Read LWC lifecycle and wire for how wires and hooks behave.
- Read LWC Jest unit testing for the testing approach in depth.
- Read LWC communication and data patterns for parent and child events.
Sources and references
Salesforce releases three times a year, so features and limits change. Always confirm against the current official documentation.
Up next
Keep reading

LWC Jest Unit Testing: Mock Apex, Wire Adapters, Events and Child Components
Unit test Lightning web components with Jest: setup, mocking Apex and wire adapters, testing events and async rendering, and running tests in CI.

LWC Communication and Data Patterns: Events, LMS, Apex and Lightning Data Service
Build a three-component LWC screen using @api, custom events, Lightning Message Service, wired Apex, updateRecord and refreshApex, with tests.

Apex Exception Handling and Logging: Custom Exceptions, Savepoints and a Log Framework
Handle Apex errors the right way: try/catch/finally, custom exceptions, partial DML results, savepoints and a platform-event logger, with full tests.
Sanjay Kumar B