Hey guys, today in this post we are going to learn about Create a record on Contact Object to insert record Id of lookup field value with passing parameters to apex class Database.insert in LWC.
Salesforce lookup relationship has no relation with other records. It does not depend on any other objects, whereas a master-detail relationship has an association with other records. To know more details, 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 : insertLookupFieldValueLwc.html
SFDX:Lightning Web Component >> New >> insertLookupFieldValueLwc.html
insertLookupFieldValueLwc.html [Lightning Web Component HTML]
<template>
<lightning-card title="Insert Lookup Field Value in LWC" style="font: size 18px; ">
<form data-name="Create_Contact">
<div class="slds slds-grid slds-wrap slds-p-around_around">
<div class="slds-col slds-size_6-of-12 slds-p-horizontal_x-small">
<div class="slds-form-element">
<div class="slds-form-element_controller">
<lightning-input type="text" label="First Name" data-type="input-field"
value={fName} name="fName" onchange={handleChangeAction}></lightning-input>
</div>
</div>
</div>
<div class="slds-col slds-size_6-of-12 slds-p-horizontal_x-small">
<div class="slds-form-element">
<div class="slds-form-element_controller">
<lightning-input type="text" label="Last Name" data-type="input-field"
value={lName} name="lName" onchange={handleChangeAction}></lightning-input>
</div>
</div>
</div>
<div class="slds-col slds-size_6-of-12">
<div class="slds-form-element">
<div class="slds-form-element_controller">
<lightning-record-edit-form object-api-name="Contact">
<lightning-input-field field-name="AccountId" data-type="input-field" value={accountId} name="accountId" onchange={handleChangeAction}>
</lightning-input-field>
</lightning-record-edit-form>
</div>
</div>
</div>
<div class="slds-col slds-size_6-of-12">
<div class="slds-form-element">
<div class="slds-form-element_controller">
<lightning-record-edit-form object-api-name="Contact">
<lightning-input-field field-name="ReportsToId" data-type="input-field" value={reportsToId} name="reportsToId" onchange={handleChangeAction}>
</lightning-input-field>
</lightning-record-edit-form>
</div>
</div>
</div>
</div>
</form>
<div class="slds-text-align_center">
<lightning-button variant="brand" label="Save" title="Save"
class="slds-m-left_x-small slds-p-right_xx-small" onclick={saveAction}>
</lightning-button>
</div>
<footer class="slds-modal__footer">
<div class="slds-col_bump-left slds-text-align_right slds-p-horizontal_x-small slds-text-align_center">
<div style="margin-right: 10px;">
<span data-elem="alert-span" style="color: #dc3545;font-weight:500;"></span>
</div>
<span class="errmsg"></span>
<span class="errmsg2"></span>
<br/>
</div>
</footer>
</lightning-card>
</template>
Create Lightning Web Component JavaScript
Step 2:- Create Lightning Web Component : insertLookupFieldValueLwc.js
SFDX:Lightning Web Component >> New >> insertLookupFieldValueLwc.js
insertLookupFieldValueLwc.js [LWC JavaScript File]
import { LightningElement,track,api } from 'lwc';
import submitContact from '@salesforce/apex/insertLookupFieldValueLwcCtrl.submitContact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
export default class InsertLookupFieldValueLwc extends NavigationMixin(LightningElement) {
recordId;
@track accountId ;
@track contactFormdata = {};
@track reportsToId;
@track fName;
@track lName;
alertElem;
connectedCallback() {
}
handleChangeAction(event){
let thisObj = event.target.value;
// console.log('thisObj# ' + thisObj);
if(thisObj == 'fName'){
this.fName = event.target.value;
// window.console.log('fName ##' + this.fName);
}
if(thisObj == 'LastName'){
this.lName = event.target.value;
// window.console.log('fName ##' + this.lName);
}
if(thisObj == 'accountId'){
this.accountId = event.target.value;
// window.console.log('accountId ##' + this.accountId);
}
if(thisObj == 'reportsToId'){
this.reportsToId = event.target.value;
// window.console.log('reportsToId ##' + this.reportsToId);
}
} //handleChanged
async saveAction(event){
let flag = true;
const contactForm = [...this.template.querySelectorAll('form[data-name="Create_Contact"] [data-type="input-field"]')];
console.log('contactFormSelector ' + contactForm);
for(const elem of contactForm) {
this.contactFormdata[elem.name] = elem.value;
}
console.log('contactFormdata',this.contactFormdata)
const data = {
conDataFyObj: this.contactFormdata,
};
console.log('contactFormdata## ',JSON.stringify(data));
if(flag){
const result = await submitContact({
jsonData: JSON.stringify(data)
});
//console.log("JSON.stringify(contactFormdata) :- "+JSON.stringify(result));
//console.log("ResultA :- "+result.status);
if (result.status == 200) {
const toastEvent = new ShowToastEvent({
title:'success',
message:'Record created successfully',
variant:'success'
});
this.dispatchEvent(toastEvent);
console.log("ResultB :- "+JSON.stringify(result));
console.log("Result_B :- "+result.contactId);
// naviagte to record page
this.navigateToRecordPage(result.contactId);
} else {
const toastEvent = new ShowToastEvent({
title: 'Failed',
message: 'Insert Failed',
variant: 'error'
});
this.dispatchEvent(toastEvent);
console.log("ResultC :- "+JSON.stringify(result));
return this.setFormError(result.message);
}
}
}
navigateToRecordPage(recordId) {
this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: {
recordId: recordId,
actionName: 'view',
},
}).then(url => {
window.location.href = url;
});
}
setFormError(errorTxt) {
if (!this.alertElem) {
this.alertElem = this.template.querySelector('[data-elem="alert-span"]');
}
this.alertElem.innerText = errorTxt;
}
}
Create Lightning Web Component Meta XML
Step 3:- Create Lightning Web Component : insertLookupFieldValueLwc.js-meta.xml
SFDX:Lightning Web Component >> New >> insertLookupFieldValueLwc.js-meta.xml
insertLookupFieldValueLwc.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>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Step 4:- Create Apex Controller : insertLookupFieldValueLwcCtrl.cls
SFDX:Create Apex Class >> New >> insertLookupFieldValueLwcCtrl.cls
insertLookupFieldValueLwcCtrl.cls [Apex Class]
public WITH sharing class insertLookupFieldValueLwcCtrl {
@AuraEnabled
public static Map<String, Object> submitContact(String jsonData) {
Map<String, Object> RESULT = NEW Map<String, Object>();
try {
Map<String, Object> formDataMap = (Map<String, Object>)JSON.deserializeUntyped(jsonData);
System.debug('jsonData ' + jsonData);
Map<String, Object> ContactDataMap = (Map<String, Object>)formDataMap.get('conDataFyObj');
system.debug('ContactDataMap## ' + ContactDataMap);
Contact conObj = NEW Contact();
conObj.FirstName=getStringValueFromMap(ContactDataMap, 'fName');
conObj.LastName=getStringValueFromMap(ContactDataMap, 'lName');
conObj.AccountId=getStringValueFromMap(ContactDataMap, 'accountId');
conObj.ReportsToId=getStringValueFromMap(ContactDataMap, 'reportsToId');
system.debug('conObj### '+ conObj);
String insertMsg;
String contactId;
List<DATABASE.SaveResult> insertResult = DATABASE.insert(NEW List<Contact>{conObj});
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(), ','));
system.debug('dbErrorArr1 ' + dbErrorArr);
}
IF(insertResultItem.isSuccess()) {
insertMsg = 'Record Created Successfully';
contactId = insertResultItem.getId();
system.debug('contactId#1 ' + contactId);
} ELSE {
insertMsg = String.join(dbErrorArr, ';');
system.debug('insertMsg1' + insertMsg);
}
}
system.debug('insertMsg## ' + insertMsg);
IF(insertMsg != NULL) {
RESULT.put('status', 200);
RESULT.put('message', insertMsg);
RESULT.put('contactId',contactId );
system.debug('result#N' + RESULT);
RETURN RESULT;
}
}catch(Exception ex) {
System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
RESULT.put('status', 500);
RESULT.put('message', ex.getMessage() + ', line : ' + ex.getLineNumber());
}
system.debug('result###B ' + RESULT);
RETURN RESULT;
}
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;
}
}
Further post that would you like to learn in Salesforce
What is Database insert in Apex?
Insert β Using Database. Insert method you can specify whether you wanted to abort the complete records when there is an error in any records or commit the success record and show a list of failed records. It also provides the Rollback functionality.
What is the difference between Database insert and insert in Apex?
Using the insert method we can insert the records but if any error occurs in any record system will throw an error insertion fail and none of the records are inserted. If we want to execute partially the success of bulk insert operation we will use database.insert.
What does Database insert returns?
The Database methods return result objects containing success or failure information for each record. For example, insert and update operations each return an array of Database. SaveResult objects.
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 |