Create multiple Contacts in Salesforce Using a Lightning Web Component (LWC) Calling an Apex method Using Database.insert for bulk record insert and Displaying success & error messages

123 views

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

๐Ÿ‘‰ Download Free Ebook โ†’

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com

Apex Class โ€” Bulk Insert Contacts

 

ContactBulkInsertController.cls โ†’

Step 1:- ContactBulkInsertController.cls

ContactBulkInsertController.cls [Apex Controller]

  1.  
  2.   public WITH sharing class ContactBulkInsertController {
  3.  
  4.     @AuraEnabled
  5.     public static String createContacts(List<Contact> contactList) {
  6.         try {
  7.             DATABASE.SaveResult[] results = DATABASE.insert(contactList, FALSE);
  8.  
  9.             INTEGER successCount = 0;
  10.             INTEGER errorCount = 0;
  11.  
  12.             FOR (DATABASE.SaveResult sr : results) {
  13.                 IF (sr.isSuccess()) {
  14.                     successCount++;
  15.                 } ELSE {
  16.                     errorCount++;
  17.                     System.debug('Error: ' + sr.getErrors()[0].getMessage());
  18.                 }
  19.             }
  20.  
  21.             RETURN 'Total: ' + contactList.size() +
  22.                    ', Success: ' + successCount +
  23.                    ', Failed: ' + errorCount;
  24.         } catch (Exception ex) {
  25.             throw NEW AuraHandledException(ex.getMessage());
  26.         }
  27.     }
  28. }

 

 

ContactBulkInsert.html โ†’

Step 2:- LWC HTML โ€” Input Fields for Multiple Contacts

ContactBulkInsert.html [HTML Component]

  1.  
  2.  <template>
  3.     <lightning-card title="Bulk Create Contacts" icon-name="standard:contact">
  4.         <div class="slds-m-around_medium">
  5.  
  6.             <template FOR:each={contacts} FOR:item="cont">
  7.                 <div KEY={cont.id} class="slds-box slds-m-bottom_small">
  8.                     <lightning-INPUT label="First Name" data-id={cont.id} VALUE={cont.FirstName}
  9.                         onchange={handleChange} name="FirstName"></lightning-input>
  10.  
  11.                     <lightning-INPUT label="Last Name" data-id={cont.id} VALUE={cont.LastName}
  12.                         onchange={handleChange} name="LastName"></lightning-input>
  13.  
  14.                     <lightning-INPUT label="Email" TYPE="email" data-id={cont.id} VALUE={cont.Email}
  15.                         onchange={handleChange} name="Email"></lightning-input>
  16.                 </div>
  17.             </template>
  18.  
  19.             <lightning-button variant="brand" label="Create Contacts"
  20.                 onclick={handleCreateContacts}></lightning-button>
  21.  
  22.         </div>
  23.     </lightning-card>
  24. </template>

 

ContactBulkInsert.js โ†’

Step 3:- LWC JavaScript โ€” Data Handling + Apex Call

ContactBulkInsert.js [HTML Component]

  1.  
  2.  import { LightningElement, track } FROM 'lwc';
  3. import createContacts FROM '@salesforce/apex/ContactBulkInsertController.createContacts';
  4. import { ShowToastEvent } FROM 'lightning/platformShowToastEvent';
  5.  
  6. export DEFAULT class ContactBulkInsert extends LightningElement {
  7.  
  8.     @track contacts = [
  9.         { id: '1', FirstName: '', LastName: '', Email: '' },
  10.         { id: '2', FirstName: '', LastName: '', Email: '' },
  11.         { id: '3', FirstName: '', LastName: '', Email: '' }
  12.     ];
  13.  
  14.     handleChange(event) {
  15.         let fieldName = event.target.name;
  16.         let recId = event.target.dataset.id;
  17.  
  18.         this.contacts = this.contacts.map(ROW => {
  19.             IF (ROW.id === recId) {
  20.                 ROW[fieldName] = event.target.value;
  21.             }
  22.             RETURN ROW;
  23.         });
  24.     }
  25.  
  26.     handleCreateContacts() {
  27.  
  28.         let validContacts = this.contacts.map(c => {
  29.             RETURN {
  30.                 FirstName: c.FirstName,
  31.                 LastName: c.LastName,
  32.                 Email: c.Email
  33.             };
  34.         });
  35.  
  36.         createContacts({ contactList: validContacts })
  37.             .then(RESULT => {
  38.                 this.showToast('Success', RESULT, 'success');
  39.             })
  40.             .catch(error => {
  41.                 this.showToast('Error', error.body.message, 'error');
  42.             });
  43.     }
  44.  
  45.     showToast(title, message, variant) {
  46.         this.dispatchEvent(NEW ShowToastEvent({ title, message, variant }));
  47.     }
  48. }

 

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]

  1.   <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>61.0</apiVersion>
  4.     <isExposed>true</isExposed>
  5.     <targets>
  6.         <target>lightning__HomePage</target>
  7.         <target>lightning__AppPage</target>
  8.         <target>lightning__RecordPage</target>
  9.     </targets>
  10. </LightningComponentBundle>

 

Further post that would you like to learn in Salesforce

 

FAQ (Frequently Asked Questions)

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 Complementary โ†’

right side banner -- www.w3webmart.com
 
  
๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Salesforce Administrators

๐Ÿ“Œ Salesforce Lightning Flow Builder

๐Ÿ“Œ Salesforce Record Trigger Flow Builder

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Aura Lightning Framework

๐Ÿ“Œ Lightning Web Component (LWC)

๐Ÿ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net