Hey guys, today in this post we are going to learn about How to Insert record Uses of Apex Framework on standard object in Salesforce LWC.
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on Salesforce servers in conjunction with calls to the API. Using syntax that looks like Java and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects. 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 : createOpt.html
SFDX:Lightning Web Component >> New >> createOpt.html
createOpt.html [Lightning Web Component HTML]
<template>
<lightning-card title="Create Opportunity">
<form data-name="opptForm">
<div class="slds-grid slds-wrap">
<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="date" class="inpFld" label="Close Date" value={optFormData.CloseDate} data-type="input-field"
name="CloseDate" required>
</lightning-input>
</div>
<div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">
<lightning-record-edit-form object-api-name="Opportunity">
<lightning-input-field field-name="StageName" class="inpFld" data-type="input-field" value={optFormData.StageName} name="StageName"
required>
</lightning-input-field>
</lightning-record-edit-form>
</div>
<div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">
<lightning-record-edit-form object-api-name="Opportunity">
<lightning-input-field field-name="TotalOpportunityQuantity" class="inpFld" data-type="input-field" value={optFormData.TotalOpportunityQuantity} name="TotalOpportunityQuantity"
required>
</lightning-input-field>
</lightning-record-edit-form>
</div>
<div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">
<lightning-record-edit-form object-api-name="Opportunity">
<lightning-input-field field-name="Amount" class="inpFld" data-type="input-field" value={optFormData.Amount} name="Amount"
required>
</lightning-input-field>
</lightning-record-edit-form>
</div>
</div>
</form>
<br/><br/>
<footer class="slds-modal__footer">
<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>
<!--Start Spinner-->
<template if:true={spinnerStatus}>
<div class="slds-is-relative">
<section class="slds-modal slds-fade-in-open">
<lightning-spinner variant="brand" alternative-text="Loading..."></lightning-spinner>
</section>
<div class="slds-backdrop slds-backdrop_open"></div>
</div>
</template>
<!--End Spinner-->
</template>
Create Lightning Web Component JavaScript
Step 2:- Create Lightning Web Component : createOpt.js
SFDX:Lightning Web Component >> New >> createOpt.js
createOpt.js [LWC JavaScript File]
import { LightningElement,api,track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import submitOptRecord from '@salesforce/apex/createOptCtrl.submitOptRecord';
import { NavigationMixin } from 'lightning/navigation';
export default class CreateOpt extends NavigationMixin (LightningElement) {
@track recordId;
@track optFormData = {};
@api spinnerStatus = false;
toastEventFire(title, msg, variant, mode) {
const e = new ShowToastEvent({
title: title,
message: msg,
variant: variant,
mode: mode
});
this.dispatchEvent(e);
}
connectedCallback() {
this.alertElem = this.template.querySelector('[data-elem="alert-span"]');
// console.log(this.alertElem);
}
async saveButtonAction(event) {
let flag = true;
this.spinnerStatus=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,
};
console.log('optDataFyObj## ',JSON.stringify(data));
if(flag){
const result = await submitOptRecord({
jsonDataStr: JSON.stringify(data)
});
console.log('result## ' , result);
const toastEvent = new ShowToastEvent({
title:'success',
message:'Record created successfully',
variant:'success'
});
this.dispatchEvent(toastEvent);
this.spinnerStatus=false;
if (result.status == 200) {
// naviagte to record page
this.navigateToRecordPage(this.opportunityId);
} else {
return this.setFormError(result.message);
}
}
}
navigateToRecordPage(recordId) {
this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: {
recordId: recordId,
actionName: 'view',
},
}).then(url => {
window.location.href = url;
});
}
}
Create Lightning Web Component Meta XML
Step 3:- Create Lightning Web Component : createOpt.js-meta.xml
SFDX:Lightning Web Component >> New >> createOpt.js-meta.xml
createOpt.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__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 Apex Class Controller
Step 4:- Create Apex Class : createOptCtrl.cls
From Developer Console >> File >> New >> Apex Class
createOptCtrl.cls [Apex Class Controller]
public WITH sharing class createOptCtrl {
@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> OptDataMap = (Map<String, Object>)formDataMap.get('optDataFyObj');
Opportunity optObj = NEW Opportunity();
optObj.Name = getStringValueFromMap(OptDataMap, 'Name');
optObj.CloseDate = getDateValueFromMap(OptDataMap, 'CloseDate');
optObj.StageName = getStringValueFromMap(OptDataMap, 'StageName');
optObj.TotalOpportunityQuantity = getIntValueFromMap(OptDataMap, 'TotalOpportunityQuantity');
optObj.Amount = getDecimalValueFromMap(OptDataMap, 'Amount');
system.debug('optObj### ' + optObj);
List<DATABASE.SaveResult> insertResult = DATABASE.insert(NEW List<Opportunity>{optObj});
System.debug('insertResult ' + insertResult);
}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;
}
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;
}
public static INTEGER getIntValueFromMap(Map<String, Object> dataMap, String fieldName) {
INTEGER VALUE;
try {
String str;
IF(dataMap.containsKey(fieldName)) {
str = String.valueOf(dataMap.get(fieldName));
}
VALUE = String.isEmpty(str) ? VALUE : INTEGER.valueOf(str);
} catch(Exception ex) {
System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
}
RETURN VALUE;
}
public static DECIMAL getDecimalValueFromMap(Map<String, Object> dataMap, String fieldName) {
DECIMAL VALUE;
try {
String str;
IF(dataMap.containsKey(fieldName)) {
str = String.valueOf(dataMap.get(fieldName));
}
VALUE = String.isEmpty(str) ? VALUE : DECIMAL.valueOf(str);
} catch(Exception ex) {
System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
}
RETURN VALUE;
}
}
Further post that would you like to learn in Salesforce
What is APEX framework?
Salesforce Apex is a Microsoft-certified framework for building software as a service (SaaS) apps on top of Salesforce's customer relationship management (CRM) functionality.
Is APEX a coding language?
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Lightning platform server in conjunction with calls to the Lightning Platform API.
What is the full form of APEX?
The full form of apex is: Adavnced Programming Experience.
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 |