Sub topic 12
Related adapters: getRecordUi, getRecordCreateDefaults, and getRecords
This chapter assumes you can already wire getRecord, use $ reactive parameters, and read data and error from a wire result. It covers three neighbouring adapters in lightning/uiRecordApi. You will see what each one returns, when it beats getRecord, and what it costs.
Where these adapters fit
All three adapters are wire adapters backed by Lightning Data Service (LDS). They share the record cache with getRecord, so the provisioning, reactivity, and data/error behavior you already know applies to them.
| Adapter | Main question it answers | Key parameters |
|---|---|---|
| `getRecord` | What are the values of these fields on one record? | `recordId`, `fields`, `optionalFields` |
| `getRecordUi` | What do the layout, metadata, and values look like for these records? | `recordIds`, `layoutTypes`, `modes`, `optionalFields` |
| `getRecordCreateDefaults` | What should a new record of this object look like? | `objectApiName`, `formFactor`, `recordTypeId`, `optionalFields` |
| `getRecords` | What are the values of these fields on several records, in one request? | `records` (a list of record requests) |
getRecordUi: layout, metadata, and data together
getRecordUi returns a record's data along with the page layout that describes how to display it. You choose a layout type (Compact or Full) and a mode (View, Edit, or Create). You can request more than one record by passing an array of IDs.
import { LightningElement, api, wire } from 'lwc';
import { getRecordUi } from 'lightning/uiRecordApi';
export default class AccountLayoutInspector extends LightningElement {
@api recordId;
sectionCount;
errorMessage;
@wire(getRecordUi, {
recordIds: '$recordId',
layoutTypes: ['Full'],
modes: ['View']
})
wiredUi({ data, error }) {
if (data) {
const record = data.records[this.recordId];
const objectApiName = record.apiName;
const recordTypeId = record.recordTypeId;
const layout = data.layouts[objectApiName][recordTypeId].Full.View;
this.sectionCount = layout.sections.length;
this.errorMessage = undefined;
} else if (error) {
this.errorMessage = error.body && error.body.message;
this.sectionCount = undefined;
}
}
}The result has three main parts:
data.recordsis an object keyed by record ID.data.layoutsis nested by object API name, then record type ID, then layout type, then mode.data.objectInfosholds object metadata such as field labels and data types.
Two details matter in practice. First, you must walk the nested layouts structure yourself, and the code above only works if the record type ID is present in that structure. For an object with no record types, the ID is the master record type ID. Second, the payload is large because you pay for layout and metadata on every request, even when you only need two field values.
Because of that cost, getRecordUi is a poor default. Use it when you are building a layout-driven display and need the layout definition itself. If you only need values, use getRecord. If you need labels or data types, pair getRecord with the getObjectInfo adapter from lightning/uiObjectInfoApi. Salesforce's reference documentation changes over time, so check it for the current guidance on getRecordUi before you build on it.
getRecordCreateDefaults: preparing a new record
When a user creates a record, the server knows things the client does not. These include default field values, the record type, and which fields appear on the create layout. getRecordCreateDefaults fetches them.
Its result contains:
data.record, a record representation filled with default values.data.objectInfos, keyed by object API name.data.layout, the create layout.
The companion function generateRecordInputForCreate turns the defaults and object metadata into the input that createRecord expects. It keeps only the fields the current user can create. createRecord is an imperative function, like updateRecord. It is not a wire adapter.
import { LightningElement, wire } from 'lwc';
import {
getRecordCreateDefaults,
generateRecordInputForCreate,
createRecord
} from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
export default class AccountQuickCreate extends LightningElement {
recordInput;
errorMessage;
@wire(getRecordCreateDefaults, {
objectApiName: ACCOUNT_OBJECT,
formFactor: 'Large'
})
wiredDefaults({ data, error }) {
if (data) {
this.recordInput = generateRecordInputForCreate(
data.record,
data.objectInfos[ACCOUNT_OBJECT.objectApiName]
);
this.errorMessage = undefined;
} else if (error) {
this.errorMessage = error.body && error.body.message;
}
}
handleNameChange(event) {
this.recordInput.fields.Name = event.target.value;
}
async handleCreate() {
try {
const created = await createRecord(this.recordInput);
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account created: ' + created.id,
variant: 'success'
})
);
} catch (error) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body && error.body.message,
variant: 'error'
})
);
}
}
}The template needs an input and a button. It renders them only after the defaults arrive.
<template>
<template lwc:if={recordInput}>
<lightning-input label="Account name" onchange={handleNameChange}></lightning-input>
<lightning-button label="Create" onclick={handleCreate}></lightning-button>
</template>
<template lwc:if={errorMessage}>
<p>{errorMessage}</p>
</template>
</template>formFactor accepts Large, Medium, or Small and selects which layout the server uses. You can also pass recordTypeId to get defaults for a specific record type, and optionalFields to request extra fields.
getRecords: several records in one request
getRecords fetches data for multiple records with a single wire. Each entry in the records array has its own recordIds, fields, and optionalFields. This lets you ask for different fields on different objects in one call.
import { LightningElement, api, wire } from 'lwc';
import { getRecords } from 'lightning/uiRecordApi';
import ACCOUNT_NAME from '@salesforce/schema/Account.Name';
import CONTACT_NAME from '@salesforce/schema/Contact.Name';
import CONTACT_EMAIL from '@salesforce/schema/Contact.Email';
export default class RelatedRecordNames extends LightningElement {
@api accountId;
@api contactId;
names = [];
failures = 0;
@wire(getRecords, {
records: [
{ recordIds: ['$accountId'], fields: [ACCOUNT_NAME] },
{ recordIds: ['$contactId'], fields: [CONTACT_NAME], optionalFields: [CONTACT_EMAIL] }
]
})
wiredRecords({ data, error }) {
if (data) {
const ok = data.results.filter((r) => r.statusCode === 200);
this.names = ok.map((r) => r.result.fields.Name.value);
this.failures = data.results.length - ok.length;
} else if (error) {
this.names = [];
this.failures = 0;
}
}
}The result shape differs from getRecord. The value is data.results, an array with one entry per requested record. Each entry has a statusCode and a result. A request can succeed overall while some entries fail, so check each statusCode instead of treating data as proof that every record loaded. The top-level error is for failures of the whole request.
The $ prefix works inside the nested arrays too. The wire waits until the referenced values are defined, so the example above does not fire until both IDs exist.
Check the current reference documentation for the availability status and request limits of getRecords before you depend on it in production.
Choosing between the adapters
Start from the narrowest adapter that answers your question:
- One record, known fields:
getRecordwithfieldsandoptionalFields. - One record, fields chosen by the layout:
getRecordwithlayoutTypesandmodes. - Layout structure or metadata for rendering:
getRecordUi, orgetRecordplusgetObjectInfo. - Several records at once:
getRecords. CallinggetRecordonce per record also works when each wire is driven by a different reactive property. - Defaults for a new record:
getRecordCreateDefaults, thencreateRecord.
Remember the split from earlier chapters: reads use wire adapters, and writes (updateRecord, createRecord) are imperative functions. If you do not need custom behavior, the base record form components may replace all of this code. They are covered in a later chapter.
Exercise
A component needs the Name field of an Account and the Name field of a related Contact. It also wants the Contact's Email if the user can see it. You prefer one wire. Which adapter fits, and how should the component check that both records loaded?
Show answer
Use getRecords with two entries in the records array. Give the Account entry fields: [Account.Name]. Give the Contact entry fields: [Contact.Name] and optionalFields: [Contact.Email], so a missing Email permission does not fail the request. Because each entry in data.results has its own statusCode, check that every entry has statusCode 200 before reading result.fields.
Exercise
You call getRecordCreateDefaults for Account and then call createRecord. Which function turns the defaults into the input that createRecord expects, and what does it need as arguments?
Show answer
generateRecordInputForCreate. It takes the defaults record (data.record) and the object metadata for the object (data.objectInfos[objectApiName]), and returns a record input containing only the fields the user can create.