Pre-populating standard or custom fields during record creation speeds up data entry, reduces human error, and improves overall user satisfaction. Using Lightning Data Service (LDS) through the lightning/uiRecordApi module allows you to create records directly on the client side with custom default values—without writing custom Apex insertion code.
Prerequisites
- A Salesforce Developer Edition, Scratch Org, or Sandbox environment.
- Salesforce CLI (
sf) installed and authenticated to your org. - Familiarity with reactive JavaScript properties and Lightning Data Service (
createRecord).
Step 1: Create the LWC Component
sf lightning generate component -n createRecordWithDefaults -d force-app/main/default/lwc --type lwc
Step 2: Build the Record Creation Template
In createRecordWithDefaults.html, construct the form interface with interactive inputs, loading indicators, and submission controls:
<template>
<lightning-card title="Create Account with Default Values" icon-name="standard:account">
<div class="slds-p-around_medium">
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Creating record..." size="small"></lightning-spinner>
</template>
<div class="slds-grid slds-gutters slds-wrap">
<div class="slds-col slds-size_1-of-1 slds-medium-size_1-of-2 slds-m-bottom_small">
<lightning-input
label="Account Name"
data-field="Name"
value={formData.Name}
onchange={handleInputChange}
required>
</lightning-input>
</div>
<div class="slds-col slds-size_1-of-1 slds-medium-size_1-of-2 slds-m-bottom_small">
<lightning-combobox
label="Rating"
data-field="Rating"
value={formData.Rating}
options={ratingOptions}
onchange={handleInputChange}>
</lightning-combobox>
</div>
<div class="slds-col slds-size_1-of-1 slds-medium-size_1-of-2 slds-m-bottom_small">
<lightning-combobox
label="Type"
data-field="Type"
value={formData.Type}
options={typeOptions}
onchange={handleInputChange}>
</lightning-combobox>
</div>
<div class="slds-col slds-size_1-of-1 slds-medium-size_1-of-2 slds-m-bottom_small">
<lightning-input
type="tel"
label="Phone"
data-field="Phone"
value={formData.Phone}
onchange={handleInputChange}>
</lightning-input>
</div>
</div>
<div class="slds-m-top_medium slds-button-group" role="group">
<lightning-button
variant="brand"
label="Create Account"
onclick={handleCreateRecord}
disabled={isLoading}>
</lightning-button>
<lightning-button
variant="neutral"
label="Reset Defaults"
onclick={handleResetDefaults}
disabled={isLoading}>
</lightning-button>
</div>
</div>
</lightning-card>
</template>
Step 3: Implement JavaScript Logic with Schema References
In createRecordWithDefaults.js, import schema references to guarantee compile-time field verification. Initialize the form state with your default business values, handle changes, and call createRecord:
import { LightningElement, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
// Strong schema imports for referential integrity
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import RATING_FIELD from '@salesforce/schema/Account.Rating';
import TYPE_FIELD from '@salesforce/schema/Account.Type';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
const DEFAULT_FORM_VALUES = {
Name: 'New Corporate Account',
Rating: 'Hot',
Type: 'Prospect',
Phone: '1-800-555-0199'
};
export default class CreateRecordWithDefaults extends LightningElement {
@track formData = { ...DEFAULT_FORM_VALUES };
isLoading = false;
get ratingOptions() {
return [
{ label: 'Hot', value: 'Hot' },
{ label: 'Warm', value: 'Warm' },
{ label: 'Cold', value: 'Cold' }
];
}
get typeOptions() {
return [
{ label: 'Prospect', value: 'Prospect' },
{ label: 'Customer - Direct', value: 'Customer - Direct' },
{ label: 'Customer - Channel', value: 'Customer - Channel' }
];
}
handleInputChange(event) {
const fieldName = event.target.dataset.field;
this.formData[fieldName] = event.target.value;
}
handleResetDefaults() {
this.formData = { ...DEFAULT_FORM_VALUES };
this.showToast('Reset Complete', 'Default values restored.', 'info');
}
async handleCreateRecord() {
// Validate required fields
const allValid = [...this.template.querySelectorAll('lightning-input, lightning-combobox')]
.reduce((validSoFar, inputCmp) => {
inputCmp.reportValidity();
return validSoFar && inputCmp.checkValidity();
}, true);
if (!allValid) {
this.showToast('Validation Error', 'Please complete all required fields.', 'error');
return;
}
this.isLoading = true;
// Map form values to schema field references
const fields = {};
fields[NAME_FIELD.fieldApiName] = this.formData.Name;
fields[RATING_FIELD.fieldApiName] = this.formData.Rating;
fields[TYPE_FIELD.fieldApiName] = this.formData.Type;
fields[PHONE_FIELD.fieldApiName] = this.formData.Phone;
const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
try {
const record = await createRecord(recordInput);
this.showToast('Success', `Account created successfully with ID: ${record.id}`, 'success');
this.handleResetDefaults();
} catch (error) {
this.showToast('Creation Error', error?.body?.message || 'Failed to create record.', 'error');
} finally {
this.isLoading = false;
}
}
showToast(title, message, variant) {
this.dispatchEvent(new ShowToastEvent({ title, message, variant }));
}
}
apiName: 'Account'). Always import them via @salesforce/schema/Object.Field. Schema imports ensure that your code doesn't break if a field is renamed and prevents administrators from accidentally deleting fields that are in active use.
- No Custom Apex Needed:
createRecordoperates through Lightning Data Service, respecting Object-Level Security (OLS) and Field-Level Security (FLS) automatically. - Cache Synchronization: Records created via
uiRecordApiupdate the local LDS cache instantly without manual page refreshes. - Alternative Approach: If you are using
lightning-record-edit-form, you can simply bind your default variables to thevalueattribute of eachlightning-input-field.
Step 4: Configure Component Metadata and Deploy
Update createRecordWithDefaults.js-meta.xml to expose the component in Lightning App Builder:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
# Deploy the component bundle
sf project deploy start
# Open your org
sf org open
- In Salesforce Setup, open Lightning App Builder.
- Place
createRecordWithDefaultsonto any Record or App Page. - Confirm that all input fields load with their pre-defined default values upon page load.
- Click Create Account to verify that the record is inserted directly into your Salesforce database.
createRecord provides an efficient, declarative, and metadata-aware method to create pre-populated Salesforce records.
Comments
Questions, corrections and your own experience are all welcome.
Post a Comment