Add Multiple Rows button (Dynamic Contact Rows) Bulk Insert Contacts Related to Account using Database.insert() in LWC Salesforce

95 views

Add Multiple Rows button (Dynamic Contact Rows) Bulk Insert Contacts Related to Account using Database.insert() Single LWC (No child component) in LWC Salesforce

SCENARIO

User will:

๐Ÿ‘‰ Download Free Ebook โ†’

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
  • Enter Account details
  • Click Add Contact Row (can add multiple contacts)
  • Fill contact details
  • Apex inserts Account + Bulk Contacts

 

Create Apex Class โ†’ AccountContactBulkController.cls

Step 1:- AccountContactBulkController.cls

AccountContactBulkController.cls [Apex Controller]

  1. public WITH sharing class AccountContactBulkController {
  2.  
  3.     @AuraEnabled
  4.     public static String accountWithAddMultiContacts(Account acc, List<Contact> contactList) {
  5.  
  6.         try {
  7.             // Step 1: INSERT Account
  8.             INSERT acc;
  9.  
  10.             // Step 2: Assign AccountId TO each Contact
  11.             FOR(Contact c : contactList){
  12.                 c.AccountId = acc.Id;
  13.             }
  14.  
  15.             // Step 3: Bulk INSERT Contacts
  16.             DATABASE.SaveResult[] results = DATABASE.insert(contactList, FALSE);
  17.  
  18.             INTEGER successCount = 0;
  19.             INTEGER failCount = 0;
  20.  
  21.             FOR(DATABASE.SaveResult sr : results){
  22.                 IF(sr.isSuccess()){
  23.                     successCount++;
  24.                 } ELSE {
  25.                     failCount++;
  26.                 }
  27.             }
  28.  
  29.             RETURN 'Account Created: ' + acc.Name +
  30.                    ' | Total Contacts: ' + contactList.size() +
  31.                    ' | Success: ' + successCount +
  32.                    ' | Failed: ' + failCount;
  33.  
  34.         } catch(Exception e){
  35.             throw NEW AuraHandledException(e.getMessage());
  36.         }
  37.     }
  38. }

 

 

Component Name: accountContactDynamic.html โ†’

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

accountContactDynamic.html [HTML Component]

  1. <template>
  2.     <lightning-card title="Create Account & Multiple Contacts">
  3.  
  4.         <div class="slds-m-around_medium">
  5.                 <div class="slds-grid slds-wrap">
  6.                      <div class="slds-col slds-size_6-of-12">
  7.                         <!-- ACCOUNT SECTION -->
  8.                         <h2>Account Details</h2>
  9.  
  10.                         <lightning-INPUT label="Account Name" name="accName" onchange={handleAccountChange}></lightning-input>
  11.                         <lightning-INPUT label="Phone" name="accPhone" onchange={handleAccountChange}></lightning-input>
  12.                         <lightning-INPUT label="Description" name="accDesc" onchange={handleAccountChange}></lightning-input>
  13.                     </div>   
  14.                  </div>
  15.                         <br/>
  16.                         <h2>Contact List</h2>
  17.  
  18.                         <div class="slds-grid slds-wrap">
  19.                         <!-- CONTACT SECTION -->
  20.  
  21.                         <template FOR:each={contactList} FOR:item="con" FOR:INDEX="index">
  22.                             <div KEY={con.key} class="slds-box slds-m-bottom_small slds-col slds-size_6-of-12">
  23.  
  24.                                 <lightning-INPUT label="First Name"
  25.                                     data-INDEX={INDEX}
  26.                                     name="FirstName"
  27.                                     VALUE={con.FirstName}
  28.                                     onchange={handleContactChange}>
  29.                                 </lightning-input>
  30.  
  31.                                 <lightning-INPUT label="Last Name"
  32.                                     data-INDEX={INDEX}
  33.                                     name="LastName"
  34.                                     VALUE={con.LastName}
  35.                                     onchange={handleContactChange}>
  36.                                 </lightning-input>
  37.  
  38.                                 <lightning-INPUT label="Email"
  39.                                     TYPE="email"
  40.                                     data-INDEX={INDEX}
  41.                                     name="Email"
  42.                                     VALUE={con.Email}
  43.                                     onchange={handleContactChange}>
  44.                                 </lightning-input>
  45.  
  46.                             </div>
  47.                         </template>
  48.                      </div>   
  49.  
  50.                         <lightning-button
  51.                             label="Add Contact Row"
  52.                             onclick={addRow}
  53.                             class="slds-m-top_small">
  54.                         </lightning-button>
  55.  
  56.                         <br/><br/>
  57.  
  58.                         <lightning-button
  59.                             label="Create Account &amp; Contacts"
  60.                             variant="brand"
  61.                             onclick={handleCreate}>
  62.                         </lightning-button>
  63.  
  64.         </div>
  65.  
  66.     </lightning-card>
  67. </template>

 

accountContactDynamic.js โ†’

Step 3:- LWC JavaScript

accountContactDynamic.js [HTML Component]

  1. import { LightningElement, track } FROM 'lwc';
  2. import accountWithAddMultiContacts FROM '@salesforce/apex/AccountContactBulkController.accountWithAddMultiContacts';
  3. import { ShowToastEvent } FROM 'lightning/platformShowToastEvent';
  4.  
  5. export DEFAULT class AccountContactDynamic extends LightningElement {
  6.  
  7.     @track accountData = {};
  8.     @track contactList = [
  9.         { KEY: 1, FirstName: '', LastName: '', Email: '' }
  10.     ];
  11.  
  12.     keyIndex = 2;
  13.  
  14.     // Handle Account FIELDS
  15.     handleAccountChange(event) {
  16.         this.accountData[event.target.name] = event.target.value;
  17.     }
  18.  
  19.     // ADD NEW Contact ROW
  20.     addRow() {
  21.         this.contactList = [
  22.             ...this.contactList,
  23.             { KEY: this.keyIndex++, FirstName: '', LastName: '', Email: '' }
  24.         ];
  25.     }
  26.  
  27.     // Handle Contact CHANGE
  28.     handleContactChange(event) {
  29.         const INDEX = event.target.dataset.index;
  30.         const fieldName = event.target.name;
  31.         const VALUE = event.target.value;
  32.  
  33.         this.contactList[INDEX][fieldName] = VALUE;
  34.     }
  35.  
  36.     // CREATE Account + Contacts
  37.     handleCreate() {
  38.  
  39.         let acc = {
  40.             Name: this.accountData.accName,
  41.             Phone: this.accountData.accPhone,
  42.             Description: this.accountData.accDesc
  43.         };
  44.  
  45.         // Remove KEY BEFORE sending TO Apex
  46.         let contactsToInsert = this.contactList.map(con => {
  47.             RETURN {
  48.                 FirstName: con.FirstName,
  49.                 LastName: con.LastName,
  50.                 Email: con.Email
  51.             };
  52.         });
  53.  
  54.         accountWithAddMultiContacts({ acc: acc, contactList: contactsToInsert })
  55.             .then(RESULT => {
  56.                 this.showToast('Success', RESULT, 'success');
  57.             })
  58.             .catch(error => {
  59.                 this.showToast('Error', error.body.message, 'error');
  60.             });
  61.     }
  62.  
  63.     showToast(title, message, variant) {
  64.         this.dispatchEvent(
  65.             NEW ShowToastEvent({
  66.                 title,
  67.                 message,
  68.                 variant
  69.             })
  70.         );
  71.     }
  72. }

 

accountContactDynamic.js-meta.xml โ†’

Step 4:- LWC accountContactDynamic.js-meta.xml

accountContactDynamic.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>

 

FAQ (Frequently Asked Questions)

How to add or remove rows dynamically in lwc?

We have three methods defined each for adding rows, removing rows and saving or creating records. addRow โ€“ This method adds an value using concat method to the array so that rows gets added. removeRow โ€“ This method removes the value using array filter method. As a result, the rows gets removed.

How do I insert more than 50,000 records in Salesforce?

you need a batch class for data more than 50000. The limit is for one transaction so if you have one query or 100 queries, total record retrieved should be less than 50000.

How to create a component dynamically in LWC?

To instantiate a component dynamically, use the managed element with the lwc:is directive in a component's HTML file. Here's an HTML template that uses . serves as a placeholder in the DOM that renders the specified dynamic component.

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