Scenario
We want to create a form in LWC where the user enters First Name, Last Name, and Email for each contact and clicks Create Contacts button to insert multiple Contact records at once.
Step-by-Step Implementation
Apex Class โ Bulk Insert Contacts
ContactBulkInsertController.cls โ
Step 1:- ContactBulkInsertController.cls
ContactBulkInsertController.cls [Apex Controller]
public WITH sharing class ContactBulkInsertController {
@AuraEnabled
public static String createContacts(List<Contact> contactList) {
try {DATABASE.SaveResult[] results = DATABASE.insert(contactList, FALSE);
INTEGER successCount = 0;
INTEGER errorCount = 0;
FOR (DATABASE.SaveResult sr : results) {
IF (sr.isSuccess()) {
successCount++;} ELSE {
errorCount++;System.debug('Error: ' + sr.getErrors()[0].getMessage());
}}RETURN 'Total: ' + contactList.size() +
', Success: ' + successCount +
', Failed: ' + errorCount;
} catch (Exception ex) {
throw NEW AuraHandledException(ex.getMessage());
}}}
ContactBulkInsert.html โ
Step 2:- LWC HTML โ Input Fields for Multiple Contacts
ContactBulkInsert.html [HTML Component]
<template>
<lightning-card title="Bulk Create Contacts" icon-name="standard:contact">
<div class="slds-m-around_medium">
<template FOR:each={contacts} FOR:item="cont">
<div KEY={cont.id} class="slds-box slds-m-bottom_small">
<lightning-INPUT label="First Name" data-id={cont.id} VALUE={cont.FirstName}
onchange={handleChange} name="FirstName"></lightning-input>
<lightning-INPUT label="Last Name" data-id={cont.id} VALUE={cont.LastName}
onchange={handleChange} name="LastName"></lightning-input>
<lightning-INPUT label="Email" TYPE="email" data-id={cont.id} VALUE={cont.Email}
onchange={handleChange} name="Email"></lightning-input>
</div>
</template>
<lightning-button variant="brand" label="Create Contacts"
onclick={handleCreateContacts}></lightning-button>
</div>
</lightning-card>
</template>
ContactBulkInsert.js โ
Step 3:- LWC JavaScript โ Data Handling + Apex Call
ContactBulkInsert.js [HTML Component]
import { LightningElement, track } FROM 'lwc';
import createContacts FROM '@salesforce/apex/ContactBulkInsertController.createContacts';
import { ShowToastEvent } FROM 'lightning/platformShowToastEvent';
export DEFAULT class ContactBulkInsert extends LightningElement {
@track contacts = [
{ id: '1', FirstName: '', LastName: '', Email: '' },
{ id: '2', FirstName: '', LastName: '', Email: '' },
{ id: '3', FirstName: '', LastName: '', Email: '' }
];handleChange(event) {
let fieldName = event.target.name;
let recId = event.target.dataset.id;
this.contacts = this.contacts.map(ROW => {
IF (ROW.id === recId) {
ROW[fieldName] = event.target.value;
}RETURN ROW;
});
}handleCreateContacts() {
let validContacts = this.contacts.map(c => {
RETURN {
FirstName: c.FirstName,
LastName: c.LastName,
Email: c.Email};});
createContacts({ contactList: validContacts })
.then(RESULT => {
this.showToast('Success', RESULT, 'success');
})
.catch(error => {
this.showToast('Error', error.body.message, 'error');
});
}showToast(title, message, variant) {
this.dispatchEvent(NEW ShowToastEvent({ title, message, variant }));
}}
ContactBulkInsert.js-meta.xml โ
Step 4:- ContactBulkInsert.js-meta.xml
|
๐ Up to 99% Off Courses (Coupon)
๐ฅ Use Promo Code: STANDARDOFFER๐ฅ ๐ Get Free Salesforce Course Access: www.thevijaykumar.w3web.net |
ContactBulkInsert.js-meta.xml [meta.xml Component]
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__HomePage</target>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Further post that would you like to learn in Salesforce
How to achieve two-way data binding in LWC?
Type twoWayDataBinding as the name of the new component and press Enter. Again, Press Enter to accept the default force-app/main/default/lwc. Goto your lwc folder, you will see one new component with the name twoWayDataBinding gets created.
What is the difference between insert and database insert?
Insert โ Insert and Database. insert method are same but Database. insert method provide you more flexibility as compared to Insert Method. If there is any exception while making DML using insert then All records will be aborted.
Which method efficiently inserts multiple records into a database?
This is a straightforward approach for inserting multiple rows into a database table in a single SQL query. Using this, we can insert multiple rows with just one command.
Related Topics | You May Also Like
|
๐ Get Free Course โ
๐ Salesforce Administrators ๐ Salesforce Lightning Flow Builder ๐ Salesforce Record Trigger Flow Builder |
๐ Get Free Course โ |




