Building interactive forms in Salesforce Lightning Web Components (LWC) is a core task for frontend developers. When standard record forms (lightning-record-form or lightning-record-edit-form) do not satisfy complex business validation needs, you can easily handle custom forms by connecting your LWC to an imperative Apex controller to execute DML database insert operations.
Prerequisites
- An active Salesforce Developer Org or Scratch Org.
- Basic knowledge of Apex programming and Lightning Web Components.
- Salesforce CLI installed and connected to your target environment.
Step 1: Set Up the Project
Create a new Salesforce DX project using the CLI in your workspace terminal:
sf project generate --name LWCDatabaseInsert
Navigate to the newly generated project directory:
cd LWCDatabaseInsert
Step 2: Create the Apex Controller
Create an Apex controller class named DatabaseInsertController.cls inside force-app/main/default/classes/. This class contains an @AuraEnabled method that handles the record instantiation and insert DML execution:
// DatabaseInsertController.cls
public with sharing class DatabaseInsertController {
@AuraEnabled
public static void insertRecord(String name, String email) {
try {
Account account = new Account();
account.Name = name;
// Ensure Email__c or another valid field API name exists in your org
account.Email__c = email;
insert as user account;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
}
AuraHandledException. Doing so exposes raw system stack traces to users and masks clean error messages in JavaScript catch blocks.
Step 3: Build the LWC Form Template
Create a new component bundle named databaseInsertForm in force-app/main/default/lwc/. In databaseInsertForm.html, construct input fields and a submit button:
<!-- databaseInsertForm.html -->
<template>
<lightning-card title="Database Insert Form" icon-name="standard:account">
<div class="slds-p-horizontal_medium slds-p-vertical_small">
<lightning-input
label="Account Name"
value={name}
onchange={handleNameChange}>
</lightning-input>
<lightning-input
label="Email"
type="email"
value={email}
onchange={handleEmailChange}>
</lightning-input>
<div class="slds-m-top_medium">
<lightning-button
label="Submit"
variant="brand"
onclick={handleSubmit}>
</lightning-button>
</div>
</div>
</lightning-card>
</template>
Step 4: Implement JavaScript Form Handler
In databaseInsertForm.js, track input states and imperatively invoke the Apex method inside a submit event handler:
.then() and .catch().
// databaseInsertForm.js
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import insertRecord from '@salesforce/apex/DatabaseInsertController.insertRecord';
export default class DatabaseInsertForm extends LightningElement {
name = '';
email = '';
handleNameChange(event) {
this.name = event.target.value;
}
handleEmailChange(event) {
this.email = event.target.value;
}
handleSubmit() {
insertRecord({ name: this.name, email: this.email })
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Record inserted successfully.',
variant: 'success'
})
);
// Clear inputs after successful save
this.name = '';
this.email = '';
})
.catch((error) => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body ? error.body.message : error,
variant: 'error'
})
);
});
}
}
Step 5: Deploy and Test Component
Expose the component in databaseInsertForm.js-meta.xml so it can be dragged onto App, Home, or Record pages via 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__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Deploy the code package to your Salesforce org using the CLI:
sf project deploy start --source-dir force-app
- Apex Binding: Annotate backend methods with
@AuraEnabled(omitcacheable=truefor DML methods). - Imperative Call: Invoke the Apex method asynchronously from JavaScript during user action events.
- Toast Feedback: Use
ShowToastEventfromlightning/platformShowToastEventto confirm record creation. - Security Rule: Enforce user object permissions in Apex using
insert as useror Security Enforcement methods.
Conclusion
Imperative Apex execution in Lightning Web Components provides complete flexibility for custom data processing and database operations. By combining LWC form handling with secure Apex DML controllers, you can build reliable, user-friendly record creation tools on the Salesforce platform.