Create a record on Contact to insert record Id of lookup field value with passing parameters to apex class Database.insert in LWC | How to insert lookup field in salesforce using apex framework in LWC | Error handling in apex LWC | Exception handling in apex | Custom error message in LWC

1,368 views


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 β†’

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

Insert Lookup Field Value in LWC -- w3web.net

 

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]

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
   
  1.    <template>
  2.     <lightning-card title="Insert Lookup Field Value in LWC" style="font: size 18px; ">
  3.         <form data-name="Create_Contact"> 
  4.         <div class="slds slds-grid slds-wrap slds-p-around_around">
  5.  
  6.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal_x-small">
  7.                 <div class="slds-form-element">               
  8.                     <div class="slds-form-element_controller">
  9.                         <lightning-input type="text" label="First Name" data-type="input-field"
  10.                                  value={fName} name="fName" onchange={handleChangeAction}></lightning-input>   
  11.                     </div>
  12.                 </div>
  13.             </div>
  14.  
  15.             <div class="slds-col slds-size_6-of-12 slds-p-horizontal_x-small">
  16.                 <div class="slds-form-element">               
  17.                     <div class="slds-form-element_controller">
  18.                         <lightning-input type="text" label="Last Name" data-type="input-field"
  19.                                  value={lName} name="lName" onchange={handleChangeAction}></lightning-input>   
  20.                     </div>
  21.                 </div>
  22.             </div>
  23.  
  24.  
  25.            <div class="slds-col slds-size_6-of-12">
  26.                <div class="slds-form-element">               
  27.                    <div class="slds-form-element_controller">
  28.                       <lightning-record-edit-form object-api-name="Contact">
  29.                           <lightning-input-field field-name="AccountId" data-type="input-field" value={accountId} name="accountId" onchange={handleChangeAction}>
  30.                           </lightning-input-field>
  31.                       </lightning-record-edit-form>   
  32.                    </div>
  33.                </div>
  34.            </div>
  35.  
  36.            <div class="slds-col slds-size_6-of-12">
  37.                <div class="slds-form-element">               
  38.                    <div class="slds-form-element_controller">
  39.                       <lightning-record-edit-form object-api-name="Contact">
  40.                           <lightning-input-field field-name="ReportsToId" data-type="input-field" value={reportsToId} name="reportsToId" onchange={handleChangeAction}>
  41.                           </lightning-input-field>
  42.                       </lightning-record-edit-form>   
  43.                    </div>
  44.                </div>
  45.            </div>
  46.  
  47.         </div>
  48.       </form>  
  49.         <div class="slds-text-align_center">
  50.             <lightning-button variant="brand" label="Save" title="Save"
  51.                 class="slds-m-left_x-small slds-p-right_xx-small" onclick={saveAction}>
  52.             </lightning-button>
  53.         </div>
  54.  
  55.  
  56.         <footer class="slds-modal__footer">
  57.             <div class="slds-col_bump-left slds-text-align_right slds-p-horizontal_x-small slds-text-align_center">
  58.                 <div style="margin-right: 10px;">
  59.                     <span data-elem="alert-span" style="color: #dc3545;font-weight:500;"></span>
  60.                 </div>
  61.                 <span class="errmsg"></span>
  62.                 <span class="errmsg2"></span>
  63.                  <br/>
  64.             </div>
  65.         </footer>
  66.  
  67.    </lightning-card>
  68. </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]

  1.    import { LightningElement,track,api } from 'lwc';
  2. import submitContact from '@salesforce/apex/insertLookupFieldValueLwcCtrl.submitContact';
  3. import { ShowToastEvent } from 'lightning/platformShowToastEvent';
  4. import { NavigationMixin } from 'lightning/navigation';
  5.  
  6. export default class InsertLookupFieldValueLwc extends NavigationMixin(LightningElement) {
  7.     recordId;
  8.     @track accountId ;   
  9.     @track contactFormdata = {};
  10.     @track reportsToId;
  11.     @track fName;
  12.     @track lName;
  13.  
  14.  
  15.     alertElem;   
  16.     connectedCallback() {
  17.  
  18.     } 
  19.  
  20.  
  21.  
  22.     handleChangeAction(event){
  23.         let thisObj = event.target.value;
  24.        // console.log('thisObj# ' + thisObj);
  25.         if(thisObj == 'fName'){
  26.             this.fName = event.target.value;  
  27.            // window.console.log('fName ##' + this.fName);
  28.         }
  29.         if(thisObj == 'LastName'){
  30.             this.lName = event.target.value;  
  31.            // window.console.log('fName ##' + this.lName);
  32.         }
  33.  
  34.         if(thisObj == 'accountId'){
  35.             this.accountId = event.target.value;  
  36.           //  window.console.log('accountId ##' + this.accountId);
  37.  
  38.  
  39.         }
  40.         if(thisObj == 'reportsToId'){
  41.             this.reportsToId = event.target.value;  
  42.            // window.console.log('reportsToId ##' + this.reportsToId);
  43.         }
  44.  
  45.     }  //handleChanged
  46.  
  47.  
  48.  
  49.     async saveAction(event){    
  50.  
  51.                 let flag = true;
  52.                 const contactForm = [...this.template.querySelectorAll('form[data-name="Create_Contact"] [data-type="input-field"]')];
  53.                 console.log('contactFormSelector ' + contactForm);
  54.  
  55.                 for(const elem of contactForm) {
  56.                     this.contactFormdata[elem.name] = elem.value;           
  57.                 }
  58.                 console.log('contactFormdata',this.contactFormdata)
  59.  
  60.                 const data = {
  61.                     conDataFyObj: this.contactFormdata,           
  62.                 };
  63.  
  64.                 console.log('contactFormdata## ',JSON.stringify(data)); 
  65.  
  66.  
  67.                 if(flag){
  68.  
  69.                         const result = await submitContact({
  70.                             jsonData: JSON.stringify(data)
  71.                         });    
  72.  
  73.                         //console.log("JSON.stringify(contactFormdata) :- "+JSON.stringify(result));
  74.                         //console.log("ResultA :- "+result.status);
  75.  
  76.  
  77.  
  78.                         if (result.status == 200) {
  79.  
  80.                             const toastEvent = new ShowToastEvent({
  81.                                 title:'success',
  82.                                 message:'Record created successfully',
  83.                                 variant:'success'
  84.                             });
  85.                             this.dispatchEvent(toastEvent);
  86.  
  87.                             console.log("ResultB :- "+JSON.stringify(result));
  88.                             console.log("Result_B :- "+result.contactId);
  89.                             // naviagte to record page
  90.                             this.navigateToRecordPage(result.contactId);
  91.  
  92.                         } else {
  93.                                 const toastEvent = new ShowToastEvent({
  94.                                 title: 'Failed',
  95.                                 message: 'Insert Failed',
  96.                                 variant: 'error'
  97.                             });
  98.                             this.dispatchEvent(toastEvent);
  99.                             console.log("ResultC :- "+JSON.stringify(result));
  100.                             return this.setFormError(result.message);
  101.                         }
  102.  
  103.                 }
  104.  
  105.     }
  106.  
  107.     navigateToRecordPage(recordId) {
  108.         this[NavigationMixin.GenerateUrl]({
  109.             type: 'standard__recordPage',
  110.             attributes: {
  111.                 recordId: recordId,
  112.                 actionName: 'view',
  113.             },
  114.         }).then(url => {
  115.             window.location.href = url;
  116.         });
  117.     }
  118.  
  119.     setFormError(errorTxt) {
  120.         if (!this.alertElem) {
  121.             this.alertElem = this.template.querySelector('[data-elem="alert-span"]');
  122.         }
  123.         this.alertElem.innerText = errorTxt;
  124.     }
  125. }

 

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]

  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>true</isExposed>
  5.     <targets> 
  6.         <target>lightning__AppPage</target>
  7.         <target>lightning__RecordPage</target>
  8.         <target>lightning__HomePage</target>
  9.     </targets>
  10. </LightningComponentBundle>

 

Step 4:- Create Apex Controller : insertLookupFieldValueLwcCtrl.cls

SFDX:Create Apex Class >> New >> insertLookupFieldValueLwcCtrl.cls

insertLookupFieldValueLwcCtrl.cls [Apex Class]

  1.     public WITH sharing class insertLookupFieldValueLwcCtrl {
  2.  
  3.     @AuraEnabled
  4.     public static Map<String, Object> submitContact(String jsonData) {
  5.         Map<String, Object> RESULT = NEW Map<String, Object>();
  6.         try {
  7.             Map<String, Object> formDataMap = (Map<String, Object>)JSON.deserializeUntyped(jsonData);
  8.             System.debug('jsonData ' + jsonData);  
  9.             Map<String, Object> ContactDataMap = (Map<String, Object>)formDataMap.get('conDataFyObj'); 
  10.             system.debug('ContactDataMap## ' + ContactDataMap);
  11.             Contact conObj = NEW Contact();
  12.             conObj.FirstName=getStringValueFromMap(ContactDataMap, 'fName');
  13.             conObj.LastName=getStringValueFromMap(ContactDataMap, 'lName');
  14.             conObj.AccountId=getStringValueFromMap(ContactDataMap, 'accountId');
  15.             conObj.ReportsToId=getStringValueFromMap(ContactDataMap, 'reportsToId');
  16.             system.debug('conObj### '+ conObj);
  17.             String insertMsg;
  18.             String contactId;
  19.  
  20.             List<DATABASE.SaveResult> insertResult = DATABASE.insert(NEW List<Contact>{conObj});
  21.  
  22.             FOR(DATABASE.SaveResult insertResultItem : insertResult) {
  23.                 System.debug('Database.SaveResult: ' + insertResultItem);
  24.  
  25.                 List<String> dbErrorArr = NEW List<String>();
  26.                 FOR(DATABASE.Error err : insertResultItem.getErrors()) {
  27.                     dbErrorArr.add(err.getMessage() + ' fields:' + String.join(err.getFields(), ','));
  28.                     system.debug('dbErrorArr1 ' + dbErrorArr);
  29.                 }
  30.                 IF(insertResultItem.isSuccess()) {
  31.                     insertMsg = 'Record Created Successfully';
  32.                     contactId = insertResultItem.getId();
  33.  
  34.                     system.debug('contactId#1 ' + contactId);
  35.                 } ELSE {
  36.                     insertMsg = String.join(dbErrorArr, ';');
  37.                     system.debug('insertMsg1' + insertMsg);
  38.                 }
  39.             }
  40.             system.debug('insertMsg## ' + insertMsg);
  41.             IF(insertMsg != NULL) {
  42.                 RESULT.put('status', 200);
  43.                 RESULT.put('message', insertMsg);
  44.                 RESULT.put('contactId',contactId );
  45.                 system.debug('result#N' + RESULT);
  46.                 RETURN RESULT;
  47.             }
  48.  
  49.         }catch(Exception ex) {
  50.             System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  51.             RESULT.put('status', 500);
  52.             RESULT.put('message', ex.getMessage() + ', line : ' + ex.getLineNumber());
  53.         }
  54.         system.debug('result###B ' + RESULT);
  55.         RETURN RESULT;
  56.     }
  57.  
  58.     public static String getStringValueFromMap(Map<String, Object> dataMap, String fieldName) {
  59.         String VALUE;
  60.         try {
  61.             IF(dataMap.containsKey(fieldName)) {
  62.                 VALUE = String.valueOf(dataMap.get(fieldName));
  63.             }
  64.  
  65.             VALUE = String.isEmpty(VALUE) ? VALUE :  String.valueOf(VALUE);
  66.         } catch(Exception ex) {
  67.             System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  68.         }
  69.  
  70.         RETURN VALUE;
  71.     }
  72.  
  73. }

 

Further post that would you like to learn in Salesforce

 

 
 

FAQ (Frequently Asked Questions)

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

 
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