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.
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 →
Other related post that would you like to learn in Salesforce
- 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<template> <lightning-card title="Create Account"> <form data-name="opptForm"> <div class="slds-grid slds-wrap slds-m-bottom_medium"> <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small"> <lightning-input type="text" class="inpFld" label="Name" data-type="input-field" name="Name" value={optFormData.Name} required> </lightning-input> </div> <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small"> <lightning-input type="text" class="inpFld" label="Phone" value={optFormData.Phone} data-type="input-field" name="Phone" required> </lightning-input> </div> <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small"> <lightning-input type="text" class="inpFld" label="Description" value={optFormData.Description} data-type="input-field" name="Description" required> </lightning-input> </div> </div> <lightning-card title="Account Contact Line Form" style="font: size 50px;;"> <div class="slds-grid slds-wrap"> <div class="slds-col slds-size_4-of-12 slds-box slds-box_small slds-m-horizontal_xx-small"> <lightning-card title="Account Contact Line 1"> <div class="slds-p-around_small"> <c-acc-contact-line data-name="line1" record-id={recordId} onlinedata={handleChildData}></c-acc-contact-line> </div> </lightning-card> </div> <div class="slds-col slds-size_4-of-12 slds-box slds-box_small slds-m-horizontal_xx-small"> <lightning-card title="Account Contact Line 2"> <div class="slds-p-around_small"> <c-acc-contact-line data-name="line2" record-id={recordId} onlinedata={handleChildData}></c-acc-contact-line> </div> </lightning-card> </div> </div> </lightning-card> </form> <br/><br/> <footer class="slds-modal__footer"> <div style="margin-right: 10px;"> <span data-elem="alert-span" style="color: #dc3545;font-weight:500;"></span> </div> <div class="slds-col_bump-left slds-text-align_center slds-p-horizontal_x-small slds-text-align_center"> <lightning-button variant="brand" label="Save" title="Save" class="slds-m-left_x-small slds-p-right_xx-small" onclick={saveButtonAction}> </lightning-button> </div> </footer> </lightning-card> </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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
import { LightningElement,track, api } from 'lwc'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import submitOptRecord from '@salesforce/apex/accLineItemCtrl.submitOptRecord'; import { NavigationMixin } from 'lightning/navigation'; export default class AccLineItemLwc extends LightningElement { @track recordId; @track optFormData = {}; @api currentVal; @api conFormData = {}; toastEventFire(title, msg, variant, mode) { const e = new ShowToastEvent({ title: title, message: msg, variant: variant, mode: mode }); this.dispatchEvent(e); } alertElem; connectedCallback() { this.alertElem = this.template.querySelector('[data-elem="alert-span"]'); // console.log(this.alertElem); } setFormError(errorTxt) { if (!this.alertElem) { this.alertElem = this.template.querySelector('[data-elem="alert-span"]'); } this.alertElem.innerText = errorTxt; } async saveButtonAction(event) { let flag = true; for (const elem of [...this.template.querySelectorAll('form[data-name="opptForm"] [data-type="input-field"]')]) { this.optFormData[elem.name] = elem.value; console.log('aaaaa' , elem.value); } console.log('optFormData## ', this.optFormData); console.log('optFormDataStringyFy',JSON.stringify(this.optFormData)); const data = { optDataFyObj: this.optFormData, contactLine: this.salesAccLineData, }; console.log('optDataFyObj##__SS ',JSON.stringify(data)); if(flag){ const result = await submitOptRecord({ jsonDataStr: JSON.stringify(data) }); const toastEvent = new ShowToastEvent({ title:'SUCCESS', message:'Record created successfully', variant:'SUCCESS' }); this.dispatchEvent(toastEvent); } } navigateToRecordPage(recordId) { this[NavigationMixin.GenerateUrl]({ type: 'standard__recordPage', attributes: { recordId: recordId, actionName: 'view', }, }).then(url => { window.location.href = url; }); } salesAccLineData = { line1: {}, line2: {}, line3: {}, line4: {}, line5: {}, line6: {} }; handleChildData(event) { //this.currentVal=event.detail; let dataset = event.target.dataset; console.log('dataset## ' , dataset); if (!dataset) return; this.salesAccLineData[dataset.name] = event.detail; console.log('EEEEE ' , this.salesAccLineData); } } |
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>55.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__HomePage</target> <target>lightning__RecordPage</target> <target>lightning__RecordAction</target> <target>lightning__UtilityBar</target> <target>lightning__Tab</target> </targets> <targetConfigs> <targetConfig targets="lightning__RecordAction"> <actionType>ScreenAction</actionType> </targetConfig> </targetConfigs> </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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<template> <form data-name="Line1"> <div class="slds-grid slds-wrap slds-p-around_medium"> <div class="slds-col slds-size_12-of-12 slds-p-around_small"> <div class="slds-sales-line-menu-1"> <lightning-input type="text" id="line1-select-FirstName" class="inpFld" label="First Name" data-type="input-field" name="FirstName" onchange={handleConChange}> </lightning-input> </div> </div> <div class="slds-col slds-size_12-of-12 slds-p-around_small"> <div class="slds-sales-line-menu-1"> <lightning-input type="text" id="line1-select-LastName" class="inpFld" label="Last Name" data-type="input-field" name="LastName" onchange={handleConChange}> </lightning-input> </div> </div> <div class="slds-col slds-size_12-of-12 slds-p-around_small"> <div class="slds-sales-line-menu-1"> <lightning-input type="text" id="line1-select-Phone" class="inpFld" label="Phone" data-type="input-field" name="Phone" onchange={handleConChange}> </lightning-input> </div> </div> <div class="slds-col slds-size_12-of-12 slds-p-around_small"> <div class="slds-sales-line-menu-1"> <lightning-input type="email" id="line1-select-Email" class="inpFld" label="Email" data-type="input-field" name="Email" onchange={handleConChange}> </lightning-input> </div> </div> </div> </form> </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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import SystemModstamp from '@salesforce/schema/Account.SystemModstamp'; import { LightningElement,track, api } from 'lwc'; export default class AccContactLine extends LightningElement { @api recordId; data = {}; constructor() { //console.log('Component AccountLine'); super(); (async () => { //console.log('calling AccountArrFromApex'); })(); } handleConChange(event) { if(event.target.name == 'FirstName'){ this.data.FirstName = event.target.value; console.log('fname## ' , this.data.FirstName ); } if(event.target.name == 'LastName'){ this.data.LastName = event.target.value; console.log('lName ', this.data.LastName); } if(event.target.name == 'Phone'){ this.data.Phone = event.target.value; console.log('Phone ', this.data.Phone); } if(event.target.name == 'Email'){ this.data.Email = event.target.value; console.log('Email ', this.data.Email); } window.console.log('data ##' + this.data); this.sendDataToParent(); } handleFirstNameChange(event){ this.data.FirstName = event.target.value; console.log('FirstName## ', FirstName); } sendDataToParent() { console.log('sendDataToParent'); const customEventObj = new CustomEvent('linedata', { detail: this.data }); this.dispatchEvent(customEventObj); } } |
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 2 3 4 5 |
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>56.0</apiVersion> <isExposed>false</isExposed> </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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
public with sharing class accLineItemCtrl { @AuraEnabled public static Map<String, Object> submitOptRecord(String jsonDataStr) { Map<String, Object> result = new Map<String, Object>(); try { Map<String, Object> formDataMap = (Map<String, Object>)JSON.deserializeUntyped(jsonDataStr); System.debug('formDataMap ' + formDataMap); Map<String, Object> accDataMap = (Map<String, Object>)formDataMap.get('optDataFyObj'); Account accObj = new Account(); accObj.Name = getStringValueFromMap(accDataMap, 'Name'); accObj.Phone = getStringValueFromMap(accDataMap, 'Phone'); accObj.Description = getStringValueFromMap(accDataMap, 'Description'); system.debug('optObj### ' + accObj); List<Database.SaveResult> insertResult = Database.insert(new List<Account>{accObj}); System.debug('insertResult ' + insertResult); String insertMsg; String accLineId; for(Database.SaveResult insertResultItem : insertResult) { System.debug('Database.SaveResult: ' + insertResultItem); List<String> dbErrorArr = new List<String>(); for(Database.Error err : insertResultItem.getErrors()) { dbErrorArr.add(err.getMessage() + ' fields:' + String.join(err.getFields(), ',')); } if(insertResultItem.isSuccess()) { insertMsg = null; accLineId = insertResultItem.getId(); } else { insertMsg = String.join(dbErrorArr, ';'); } } system.debug('accLineId###___A' + accLineId); if(insertMsg != null) { result.put('status', 400); result.put('message', insertMsg); return result; } List<Contact> conRecArr = new List<Contact>(); system.debug('accLineId## ' + accLineId); if(accLineId != null) { Map<String, Object> lineData = (Map<String, Object>)formDataMap.get('contactLine'); system.debug('lineData_1## ' + lineData); if(lineData.containsKey('line1')) { Contact conRec = getSALObj((Map<String, Object>)lineData.get('line1'), accLineId); conRecArr.add(conRec); } if(lineData.containsKey('line1')) { Contact conRec = getSALObj((Map<String, Object>)lineData.get('line2'), accLineId); system.debug('lineData_2## ' + lineData); conRecArr.add(conRec); } System.debug('conRecArr## ' + conRecArr); insertResult = new List<Database.SaveResult>(); insertResult = Database.insert(conRecArr); System.debug('insertResult ' + insertResult); insertMsg = null; List<String> accIdArr = new List<String>(); for(Database.SaveResult insertResultItem : insertResult) { System.debug('Database.SaveResult: ' + insertResultItem); List<String> dbErrorArr = new List<String>(); for(Database.Error err : insertResultItem.getErrors()) { dbErrorArr.add(err.getMessage() + ' fields:' + String.join(err.getFields(), ',')); } if(insertResultItem.isSuccess()) { accIdArr.add(insertResultItem.getId()); } else { insertMsg = String.join(dbErrorArr, ';'); } } system.debug('accIdArr__RR' + accIdArr); if(insertMsg != null) { result.put('status', 400); result.put('message', insertMsg); return result; } else { result.put('status', 200); result.put('accLineId', accLineId); result.put('Contact Account Line Id Arr', accIdArr); return result; } } }catch(Exception ex) { System.debug('Exception ' + ex.getMessage() + ',line' + ex.getLineNumber()); result.put('status', 500); result.put('message', 'Exception ' + ex.getMessage() + ',line' + ex.getLineNumber()); } return result; } @Auraenabled public static Contact getConObj(Map<String, Object> dataMap, String accLineId) { String FirstName, LastName, Email, Phone, masterid = accLineId; FirstName = getStringValueFromMap(dataMap, 'FirstName'); Contact coObj=new Contact(); return coObj; } public static String getStringValueFromMap(Map<String, Object> dataMap, String fieldName) { String value; try { if(dataMap.containsKey(fieldName)) { value = String.valueOf(dataMap.get(fieldName)); } value = String.isEmpty(value) ? value : String.valueOf(value); } catch(Exception ex) { System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber()); } return value; } public static Date getDateValueFromMap(Map<String, Object> dataMap, String fieldName) { Date value; try { String str; if(dataMap.containsKey(fieldName)) { str = String.valueOf(dataMap.get(fieldName)); } value = String.isEmpty(str) ? value : Date.valueOf(str); } catch(Exception ex) { System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber()); } return value; } @Auraenabled public static Contact getSALObj(Map<String, Object> dataMap, String accLineId) { String fName, lName, phoneStr, emailStr, masterid = accLineId; fName = getStringValueFromMap(dataMap, 'FirstName'); lName = getStringValueFromMap(dataMap, 'LastName'); phoneStr = getStringValueFromMap(dataMap, 'Phone'); emailStr = getStringValueFromMap(dataMap, 'Email'); Contact con1 = new Contact(); con1.FirstName=fName; con1.LastName=lName; con1.Phone=phoneStr; con1.Email=emailStr; con1.AccountId=accLineId; return con1; } } |
Further post that would you like to learn in Salesforce
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
- Your reaction of the article ▾