How to create account related contacts automatically uses of LWC Apex Framework based on database.insert bulk records in Salesforce – LWC | Create Contact automatically whenever Account is created using LWC object Apex Framework in LWC – Lightning Web Component Salesforce | How to create LWC for Account with Contact at the same time through Apex Object Framework in LWC Salesforce

2,232 views


Hey guys, today in this post we are going to learn about Create Contact Automatically whenever Account is created using LWC object Apex Framework in LWC.

Expose Apex Methods to Lightning Web Components

To expose an Apex method to a Lightning web component, the method must be static and either global or public. Annotate the method with @AuraEnabled.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

These types are supported for input and output.

  • Primitive—Boolean, Date, DateTime, Decimal, Double, Integer, Long, and String.
  • sObject—standard and custom sObjects are both supported.
  • Apex—an instance of an Apex class. (Most often a custom class.)
  • Collection—a collection of any of the other types.

→ To know more details about Apex Methods, Click Here…

Final Output →

lwc apex framework to create account with contact -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

 

  • Find the below steps ▾

 

Create Lightning Web Component HTML

Step 1:- Create Lightning Web Component : accLineItemLwc.html

SFDX:Lightning Web Component >> New >> accLineItemLwc.html

accLineItemLwc.html [Lightning Web Component HTML]

  1.   <template>
  2.     <lightning-card title="Create Account">
  3.         <form data-name="opptForm">
  4.             <div class="slds-grid slds-wrap slds-m-bottom_medium">
  5.  
  6.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">                    
  7.                         <lightning-input type="text" class="inpFld" label="Name" data-type="input-field"
  8.                             name="Name" value={optFormData.Name} required>
  9.                         </lightning-input>                    
  10.                 </div>
  11.  
  12.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">                    
  13.                         <lightning-input type="text" class="inpFld" label="Phone" value={optFormData.Phone} data-type="input-field"
  14.                             name="Phone" required>
  15.                         </lightning-input>
  16.                 </div>
  17.  
  18.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">                    
  19.                     <lightning-input type="text" class="inpFld" label="Description" value={optFormData.Description} data-type="input-field"
  20.                         name="Description" required>
  21.                     </lightning-input>
  22.             </div>
  23.  
  24.             </div>
  25.  
  26.             <lightning-card title="Account Contact Line Form" style="font: size 50px;;">
  27.                <div class="slds-grid slds-wrap">
  28.  
  29.                 <div class="slds-col slds-size_4-of-12 slds-box slds-box_small slds-m-horizontal_xx-small">
  30.                     <lightning-card title="Account Contact Line 1">
  31.                         <div class="slds-p-around_small">
  32.                             <c-acc-contact-line data-name="line1" record-id={recordId}
  33.                                 onlinedata={handleChildData}></c-acc-contact-line>
  34.                         </div>
  35.                     </lightning-card>
  36.                 </div>
  37.  
  38.                 <div class="slds-col slds-size_4-of-12 slds-box slds-box_small slds-m-horizontal_xx-small">
  39.                     <lightning-card title="Account Contact Line 2">
  40.                         <div class="slds-p-around_small">
  41.                             <c-acc-contact-line data-name="line2" record-id={recordId}
  42.                                 onlinedata={handleChildData}></c-acc-contact-line>
  43.                         </div>
  44.                     </lightning-card>
  45.                 </div>
  46.  
  47.                </div>
  48.             </lightning-card>           
  49.  
  50.         </form>
  51. <br/><br/>
  52.         <footer class="slds-modal__footer">
  53.             <div style="margin-right: 10px;">
  54.                 <span data-elem="alert-span" style="color: #dc3545;font-weight:500;"></span>
  55.             </div>
  56.  
  57.             <div class="slds-col_bump-left slds-text-align_center slds-p-horizontal_x-small slds-text-align_center">
  58.                 <lightning-button variant="brand" label="Save" title="Save"
  59.                     class="slds-m-left_x-small slds-p-right_xx-small" onclick={saveButtonAction}>
  60.                 </lightning-button>
  61.             </div>
  62.         </footer>
  63.     </lightning-card>
  64. </template>

 

Create Lightning Web Component JavaScript

Step 2:- Create Lightning Web Component : accLineItemLwc.js

SFDX:Lightning Web Component >> New >> accLineItemLwc.js

accLineItemLwc.js [LWC JavaScript File]

  1.    import { LightningElement,track, api } from 'lwc';
  2. import { ShowToastEvent } from 'lightning/platformShowToastEvent';
  3. import submitOptRecord from '@salesforce/apex/accLineItemCtrl.submitOptRecord';
  4. import { NavigationMixin } from 'lightning/navigation';
  5.  
  6.  
  7. export default class AccLineItemLwc extends LightningElement {
  8.  
  9.  
  10.     @track recordId;
  11.     @track optFormData = {};
  12.     @api currentVal;
  13.  
  14.     @api conFormData = {};
  15.  
  16.     toastEventFire(title, msg, variant, mode) {
  17.         const e = new ShowToastEvent({
  18.             title: title,
  19.             message: msg,
  20.             variant: variant,
  21.             mode: mode
  22.         });
  23.         this.dispatchEvent(e);
  24.     }
  25.  
  26.     alertElem;
  27.  
  28.     connectedCallback() {
  29.         this.alertElem = this.template.querySelector('[data-elem="alert-span"]');
  30.         // console.log(this.alertElem);
  31.     }
  32.  
  33.     setFormError(errorTxt) {
  34.         if (!this.alertElem) {
  35.             this.alertElem = this.template.querySelector('[data-elem="alert-span"]');
  36.         }
  37.         this.alertElem.innerText = errorTxt;
  38.     }
  39.  
  40.     async saveButtonAction(event) {
  41.  
  42.         let flag = true;
  43.  
  44.         for (const elem of [...this.template.querySelectorAll('form[data-name="opptForm"] [data-type="input-field"]')]) {
  45.             this.optFormData[elem.name] = elem.value;
  46.             console.log('aaaaa' , elem.value);
  47.         }
  48.  
  49.  
  50.  
  51.         console.log('optFormData## ', this.optFormData);
  52.         console.log('optFormDataStringyFy',JSON.stringify(this.optFormData));
  53.  
  54.  
  55.  
  56.         const data = {
  57.             optDataFyObj: this.optFormData,
  58.             contactLine: this.salesAccLineData,           
  59.         };
  60.  
  61.         console.log('optDataFyObj##__SS ',JSON.stringify(data));
  62.  
  63.         if(flag){
  64.             const result = await submitOptRecord({                
  65.                 jsonDataStr: JSON.stringify(data)
  66.  
  67.             });
  68.  
  69.  
  70.             const toastEvent = new ShowToastEvent({
  71.                 title:'SUCCESS',
  72.                 message:'Record created successfully',
  73.                 variant:'SUCCESS'
  74.                });
  75.                this.dispatchEvent(toastEvent);
  76.  
  77.  
  78.  
  79.         }
  80.  
  81.     }
  82.  
  83.     navigateToRecordPage(recordId) {
  84.         this[NavigationMixin.GenerateUrl]({
  85.             type: 'standard__recordPage',
  86.             attributes: {
  87.                 recordId: recordId,
  88.                 actionName: 'view',
  89.             },
  90.         }).then(url => {
  91.             window.location.href = url;
  92.         });
  93.     }
  94.  
  95.  
  96.  
  97.     salesAccLineData = {
  98.         line1: {},
  99.         line2: {},
  100.         line3: {},
  101.         line4: {},
  102.         line5: {},
  103.         line6: {}
  104.     };
  105.  
  106.     handleChildData(event) {
  107.         //this.currentVal=event.detail;
  108.  
  109.         let dataset = event.target.dataset;
  110.          console.log('dataset##  ' , dataset);
  111.         if (!dataset) return;
  112.  
  113.         this.salesAccLineData[dataset.name] = event.detail;
  114.         console.log('EEEEE ' , this.salesAccLineData);
  115.  
  116.     }
  117.  
  118. }

 

Create Lightning Web Component Meta XML

Step 3:- Create Lightning Web Component : accLineItemLwc.js-meta.xml

SFDX:Lightning Web Component >> New >> accLineItemLwc.js-meta.xml

accLineItemLwc.js-meta.xml [LWC Meta Data XML]

  1.    <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>55.0</apiVersion>
  4.     <isExposed>true</isExposed>
  5.     <targets>
  6.         <target>lightning__AppPage</target>
  7.         <target>lightning__HomePage</target>
  8.         <target>lightning__RecordPage</target>
  9.         <target>lightning__RecordAction</target>
  10.         <target>lightning__UtilityBar</target>
  11.         <target>lightning__Tab</target>
  12.     </targets>
  13.     <targetConfigs>
  14.         <targetConfig targets="lightning__RecordAction">
  15.             <actionType>ScreenAction</actionType>
  16.         </targetConfig>
  17.     </targetConfigs>
  18. </LightningComponentBundle>

 

Create Lightning Web Component HTML

Step 4:- Create Lightning Web Component : accContactLine.html

SFDX:Lightning Web Component >> New >> accContactLine.html

accContactLine.html [Lightning Web Component HTML]

  1.   <template>
  2.     <form data-name="Line1">
  3.         <div class="slds-grid slds-wrap slds-p-around_medium">
  4.             <div class="slds-col slds-size_12-of-12 slds-p-around_small">
  5.                 <div class="slds-sales-line-menu-1">
  6.                     <lightning-input type="text" id="line1-select-FirstName" class="inpFld" label="First Name" data-type="input-field"
  7.                      name="FirstName" onchange={handleConChange}>
  8.                     </lightning-input>
  9.                 </div>
  10.             </div>
  11.  
  12.             <div class="slds-col slds-size_12-of-12 slds-p-around_small">
  13.                 <div class="slds-sales-line-menu-1">
  14.                     <lightning-input type="text" id="line1-select-LastName" class="inpFld" label="Last Name" data-type="input-field"
  15.                        name="LastName" onchange={handleConChange}>
  16.                     </lightning-input>
  17.                 </div>
  18.             </div>
  19.  
  20.             <div class="slds-col slds-size_12-of-12 slds-p-around_small">
  21.                 <div class="slds-sales-line-menu-1">
  22.                     <lightning-input type="text" id="line1-select-Phone" class="inpFld" label="Phone" data-type="input-field"
  23.                        name="Phone" onchange={handleConChange}>
  24.                     </lightning-input>
  25.                 </div>
  26.             </div>
  27.  
  28.             <div class="slds-col slds-size_12-of-12 slds-p-around_small">
  29.                 <div class="slds-sales-line-menu-1">
  30.                     <lightning-input type="email" id="line1-select-Email" class="inpFld" label="Email" data-type="input-field"
  31.                        name="Email" onchange={handleConChange}>
  32.                     </lightning-input>
  33.                 </div>
  34.             </div>
  35.  
  36.         </div>  
  37.     </form>   
  38. </template>

 

Create Lightning Web Component JavaScript

Step 5:- Create Lightning Web Component : accContactLine.js

SFDX:Lightning Web Component >> New >> accContactLine.js

accContactLine.js [LWC JavaScript File]

  1.    import SystemModstamp from '@salesforce/schema/Account.SystemModstamp';
  2. import { LightningElement,track, api } from 'lwc';
  3.  
  4. export default class AccContactLine extends LightningElement {
  5.     @api recordId;
  6.  
  7.     data = {};
  8.  
  9.  
  10.     constructor() {
  11.         //console.log('Component AccountLine');
  12.         super();
  13.         (async () => {
  14.  
  15.             //console.log('calling AccountArrFromApex');
  16.  
  17.  
  18.         })();
  19.     }
  20.  
  21.  
  22.     handleConChange(event) {
  23.  
  24.         if(event.target.name == 'FirstName'){           
  25.            this.data.FirstName = event.target.value;
  26.            console.log('fname## ' , this.data.FirstName );
  27.         }
  28.         if(event.target.name == 'LastName'){           
  29.             this.data.LastName = event.target.value;
  30.             console.log('lName ', this.data.LastName);
  31.          }
  32.          if(event.target.name == 'Phone'){           
  33.             this.data.Phone = event.target.value;
  34.             console.log('Phone ', this.data.Phone);
  35.          }
  36.          if(event.target.name == 'Email'){           
  37.             this.data.Email = event.target.value;
  38.             console.log('Email ', this.data.Email);
  39.          }
  40.  
  41.         window.console.log('data ##' + this.data);
  42.         this.sendDataToParent();
  43.  
  44.     }
  45.  
  46.  
  47.     handleFirstNameChange(event){
  48.         this.data.FirstName = event.target.value;
  49.         console.log('FirstName## ', FirstName);
  50.     }
  51.  
  52.     sendDataToParent() {
  53.  
  54.         console.log('sendDataToParent');
  55.         const customEventObj = new CustomEvent('linedata', {
  56.  
  57.             detail: this.data
  58.         });
  59.         this.dispatchEvent(customEventObj);
  60.     }
  61.  
  62. }

 

Create Lightning Web Component Meta XML

Step 6:- Create Lightning Web Component : accContactLine.js-meta.xml

SFDX:Lightning Web Component >> New >> accContactLine.js-meta.xml

accContactLine.js-meta.xml [LWC Meta Data XML]

  1.    <?xml version="1.0" encoding="UTF-8"?>
  2. <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  3.     <apiVersion>56.0</apiVersion>
  4.     <isExposed>false</isExposed>
  5. </LightningComponentBundle>

 

Create Apex Class Controller

Step 7:- Create Apex Class : accLineItemCtrl.cls

From Developer Console >> File >> New >> Apex Class

accLineItemCtrl.cls [Apex Class Controller]

  1.    public WITH sharing class accLineItemCtrl {
  2.  
  3.  
  4.     @AuraEnabled
  5.     public static Map<String, Object> submitOptRecord(String jsonDataStr) {
  6.         Map<String, Object> RESULT = NEW Map<String, Object>();
  7.         try {
  8.             Map<String, Object> formDataMap = (Map<String, Object>)JSON.deserializeUntyped(jsonDataStr);
  9.             System.debug('formDataMap ' + formDataMap);
  10.             Map<String, Object> accDataMap = (Map<String, Object>)formDataMap.get('optDataFyObj');
  11.  
  12.             Account accObj = NEW Account();
  13.             accObj.Name = getStringValueFromMap(accDataMap, 'Name');
  14.             accObj.Phone = getStringValueFromMap(accDataMap, 'Phone');
  15.             accObj.Description = getStringValueFromMap(accDataMap, 'Description');
  16.  
  17.  
  18.  
  19.             system.debug('optObj### ' + accObj);
  20.             List<DATABASE.SaveResult> insertResult = DATABASE.insert(NEW List<Account>{accObj});
  21.             System.debug('insertResult ' + insertResult);
  22.  
  23.             String insertMsg;
  24.             String accLineId;
  25.             FOR(DATABASE.SaveResult insertResultItem : insertResult) {
  26.                 System.debug('Database.SaveResult: ' + insertResultItem);
  27.                 List<String> dbErrorArr = NEW List<String>();
  28.  
  29.                 FOR(DATABASE.Error err : insertResultItem.getErrors()) {
  30.                     dbErrorArr.add(err.getMessage() + ' fields:' + String.join(err.getFields(), ','));
  31.                 }
  32.                 IF(insertResultItem.isSuccess()) {
  33.                     insertMsg = NULL;
  34.                     accLineId = insertResultItem.getId();                    
  35.                 } ELSE {
  36.                     insertMsg = String.join(dbErrorArr, ';');
  37.                 }
  38.  
  39.             }
  40.             system.debug('accLineId###___A' + accLineId);
  41.  
  42.  
  43.  
  44.             IF(insertMsg != NULL) {
  45.                 RESULT.put('status', 400);
  46.                 RESULT.put('message', insertMsg);
  47.                 RETURN RESULT;
  48.             }
  49.  
  50.  
  51.             List<Contact> conRecArr = NEW List<Contact>();
  52.             system.debug('accLineId## ' + accLineId);
  53.             IF(accLineId != NULL) {
  54.  
  55.                 Map<String, Object> lineData = (Map<String, Object>)formDataMap.get('contactLine');
  56.                 system.debug('lineData_1## ' + lineData);
  57.                 IF(lineData.containsKey('line1')) {
  58.                     Contact conRec = getSALObj((Map<String, Object>)lineData.get('line1'), accLineId);    
  59.                     conRecArr.add(conRec);
  60.  
  61.                 }
  62.  
  63.                 IF(lineData.containsKey('line1')) {
  64.                     Contact conRec = getSALObj((Map<String, Object>)lineData.get('line2'), accLineId);    
  65.                     system.debug('lineData_2## ' + lineData);     
  66.                     conRecArr.add(conRec);
  67.  
  68.                 }
  69.  
  70.                 System.debug('conRecArr## ' + conRecArr);
  71.                 insertResult = NEW List<DATABASE.SaveResult>();
  72.                 insertResult = DATABASE.insert(conRecArr);
  73.                 System.debug('insertResult ' + insertResult);
  74.  
  75.  
  76.                 insertMsg = NULL;
  77.                 List<String> accIdArr = NEW List<String>();
  78.                 FOR(DATABASE.SaveResult insertResultItem : insertResult) {
  79.                     System.debug('Database.SaveResult: ' + insertResultItem);
  80.                     List<String> dbErrorArr = NEW List<String>();
  81.                     FOR(DATABASE.Error err : insertResultItem.getErrors()) {
  82.                         dbErrorArr.add(err.getMessage() + ' fields:' + String.join(err.getFields(), ','));
  83.                     }
  84.                     IF(insertResultItem.isSuccess()) {
  85.                         accIdArr.add(insertResultItem.getId());
  86.                     } ELSE {
  87.                         insertMsg = String.join(dbErrorArr, ';');
  88.                     }
  89.  
  90.                 }
  91.                 system.debug('accIdArr__RR' + accIdArr);
  92.  
  93.                 IF(insertMsg != NULL) {
  94.                     RESULT.put('status', 400);
  95.                     RESULT.put('message', insertMsg);
  96.                     RETURN RESULT;
  97.                 } ELSE {
  98.                     RESULT.put('status', 200);
  99.                     RESULT.put('accLineId', accLineId);
  100.                     RESULT.put('Contact Account Line Id Arr', accIdArr);
  101.                     RETURN RESULT;
  102.                 }
  103.             }
  104.         }catch(Exception ex) {
  105.             System.debug('Exception ' + ex.getMessage() + ',line' + ex.getLineNumber());
  106.             RESULT.put('status', 500);
  107.             RESULT.put('message', 'Exception ' + ex.getMessage() + ',line' + ex.getLineNumber());
  108.         }
  109.         RETURN RESULT;
  110.  
  111.     }
  112.  
  113.  
  114.     @Auraenabled 
  115.     public static Contact getConObj(Map<String, Object> dataMap, String accLineId) {
  116.         String FirstName, LastName, Email, Phone, masterid = accLineId;
  117.         FirstName = getStringValueFromMap(dataMap, 'FirstName');
  118.  
  119.         Contact coObj=NEW Contact();
  120.  
  121.        RETURN coObj;
  122.  
  123.     }
  124.  
  125.  
  126.     public static String getStringValueFromMap(Map<String, Object> dataMap, String fieldName) {
  127.         String VALUE;
  128.         try {
  129.             IF(dataMap.containsKey(fieldName)) {
  130.                 VALUE = String.valueOf(dataMap.get(fieldName));
  131.             }
  132.  
  133.             VALUE = String.isEmpty(VALUE) ? VALUE :  String.valueOf(VALUE);
  134.         } catch(Exception ex) {
  135.             System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  136.         }
  137.  
  138.         RETURN VALUE;
  139.     }
  140.  
  141.  
  142.  
  143.     public static DATE getDateValueFromMap(Map<String, Object> dataMap, String fieldName) {
  144.         DATE VALUE;
  145.         try {
  146.             String str;
  147.             IF(dataMap.containsKey(fieldName)) {
  148.                 str = String.valueOf(dataMap.get(fieldName));
  149.             }
  150.  
  151.             VALUE = String.isEmpty(str) ? VALUE :  DATE.valueOf(str);
  152.         } catch(Exception ex) {
  153.             System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  154.         }
  155.  
  156.         RETURN VALUE;
  157.     }
  158.  
  159.  
  160.     @Auraenabled 
  161.     public static Contact getSALObj(Map<String, Object> dataMap, String accLineId) {
  162.         String fName, lName, phoneStr, emailStr, masterid = accLineId;
  163.         fName = getStringValueFromMap(dataMap, 'FirstName');
  164.         lName = getStringValueFromMap(dataMap, 'LastName');
  165.         phoneStr = getStringValueFromMap(dataMap, 'Phone');
  166.         emailStr = getStringValueFromMap(dataMap, 'Email');
  167.  
  168.           Contact con1 = NEW Contact();
  169.           con1.FirstName=fName;
  170.           con1.LastName=lName;
  171.           con1.Phone=phoneStr;
  172.           con1.Email=emailStr;
  173.           con1.AccountId=accLineId;
  174.           RETURN con1;
  175.  
  176.     }
  177.  
  178. }

 

 

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

Which framework is used for LWC testing?

Jest is a JavaScript testing Framework which focuses on simplicity. It works with Babel, TypeScript, Node, React, Angular, Vue, and more projects. Jest tests are only local and are saved and run independently of Salesforce. Jest tests are fast as they don't run in a browser or connect to an org.

How do I use APEX with LWC?

Step1: Create LWC component after creating project in vs code. Step2: Create a class in APEX CLASS and paste the below code. Step3: Paste the below HTML to the HTML file of LWC. On clicking on the button Load Accounts it will call the handleLoad event defined in the JS file.

Is Aura and LWC same?

Aura and LWC are two popular frameworks for building web applications. Aura is a framework for creating components that can be used in any web application. LWC is a framework for creating Lightning Web Components, which are components that are designed to work with the Lightning platform.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses →

👉 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

Leave a Comment