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 →
You can download file directly from github by Click Here.
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]
<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]
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]
<?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]
<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]
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]
<?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]
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
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 |