Create record dynamically Using LWC Apex Framework based on database.insert in Salesforce | Create record in bulk with database.insert and display loading spinner using LWC JavaScript | Insert record Uses of Apex Framework on standard object in Salesforce LWC

800 views

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

lwc apex framework salesforce 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 : createOpt.html

SFDX:Lightning Web Component >> New >> createOpt.html

createOpt.html [Lightning Web Component HTML]

  1.     <template>
  2.     <lightning-card title="Create Opportunity">
  3.         <form data-name="opptForm">
  4.             <div class="slds-grid slds-wrap">
  5.  
  6.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">                    
  7.                         <lightning-input type="text" class="inpFld" label="Name" data-type="input-field"
  8.                             name="Name" value={optFormData.Name} required>
  9.                         </lightning-input>                    
  10.                 </div>
  11.  
  12.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">                    
  13.                         <lightning-input type="date" class="inpFld" label="Close Date" value={optFormData.CloseDate} data-type="input-field"
  14.                             name="CloseDate" required>
  15.                         </lightning-input>
  16.                 </div>
  17.  
  18.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">
  19.                     <lightning-record-edit-form object-api-name="Opportunity">                            
  20.                         <lightning-input-field field-name="StageName" class="inpFld" data-type="input-field" value={optFormData.StageName}  name="StageName" 
  21.                         required>
  22.                         </lightning-input-field>
  23.                     </lightning-record-edit-form>
  24.                 </div>
  25.  
  26.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">
  27.                     <lightning-record-edit-form object-api-name="Opportunity">                            
  28.                         <lightning-input-field field-name="TotalOpportunityQuantity" class="inpFld" data-type="input-field" value={optFormData.TotalOpportunityQuantity}  name="TotalOpportunityQuantity" 
  29.                         required>
  30.                         </lightning-input-field>
  31.                     </lightning-record-edit-form>
  32.                 </div>
  33.  
  34.                 <div class="slds-col slds-size_3-of-12 slds-p-horizontal_x-small">
  35.                     <lightning-record-edit-form object-api-name="Opportunity">                            
  36.                         <lightning-input-field field-name="Amount" class="inpFld" data-type="input-field" value={optFormData.Amount}  name="Amount" 
  37.                         required>
  38.                         </lightning-input-field>
  39.                     </lightning-record-edit-form>
  40.                 </div>
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.             </div>
  48.         </form>
  49. <br/><br/>
  50.         <footer class="slds-modal__footer">
  51.             <div class="slds-col_bump-left slds-text-align_center slds-p-horizontal_x-small slds-text-align_center">
  52.                 <lightning-button variant="brand" label="Save" title="Save"
  53.                     class="slds-m-left_x-small slds-p-right_xx-small" onclick={saveButtonAction}>
  54.                 </lightning-button>
  55.             </div>
  56.         </footer>
  57.     </lightning-card>
  58.  
  59.  
  60.     <!--Start Spinner-->
  61.     <template if:true={spinnerStatus}>
  62.         <div class="slds-is-relative">
  63.             <section  class="slds-modal slds-fade-in-open">                
  64.                     <lightning-spinner variant="brand" alternative-text="Loading..."></lightning-spinner>                
  65.             </section>
  66.             <div class="slds-backdrop slds-backdrop_open"></div>
  67.         </div>
  68.  
  69.     </template> 
  70.     <!--End Spinner-->
  71.  
  72.  
  73. </template>

 

Create Lightning Web Component JavaScript

Step 2:- Create Lightning Web Component : createOpt.js

 
βœͺ The Big Announcement: -
As per student's demands, I re-opened my eBook of "Salesforce Tutorial" Limited-time huge discount offer Absolutely 50% Off.
I am thinking to give you discount offer occasion of Gandhi Jayanti for a powerful "Salesforce admin course" where you can Understand from Basic Concepts to advanced label in Salesforce.
πŸ‘‰ So Don't MISS it... (Access Right Now)
πŸ‘‰ Get Huge Discount Offer 50%: - Get eBook
 

SFDX:Lightning Web Component >> New >> createOpt.js

createOpt.js [LWC JavaScript File]

  1.    import { LightningElement,api,track } from 'lwc';
  2. import { ShowToastEvent } from 'lightning/platformShowToastEvent';
  3. import submitOptRecord from '@salesforce/apex/createOptCtrl.submitOptRecord';
  4. import { NavigationMixin } from 'lightning/navigation';
  5.  
  6. export default class CreateOpt extends NavigationMixin (LightningElement) {
  7.     @track recordId;
  8.     @track optFormData = {};
  9.     @api spinnerStatus = false;
  10.  
  11.     toastEventFire(title, msg, variant, mode) {
  12.         const e = new ShowToastEvent({
  13.             title: title,
  14.             message: msg,
  15.             variant: variant,
  16.             mode: mode
  17.         });
  18.         this.dispatchEvent(e);
  19.     }
  20.  
  21.     connectedCallback() {
  22.         this.alertElem = this.template.querySelector('[data-elem="alert-span"]');
  23.         // console.log(this.alertElem);
  24.     }
  25.  
  26.     async saveButtonAction(event) {
  27.  
  28.         let flag = true;
  29.         this.spinnerStatus=true;
  30.  
  31.         for (const elem of [...this.template.querySelectorAll('form[data-name="opptForm"] [data-type="input-field"]')]) {
  32.             this.optFormData[elem.name] = elem.value;
  33.             //console.log('aaaaa' , elem.value);
  34.         }
  35.  
  36.         console.log('optFormData## ', this.optFormData);
  37.         console.log('optFormDataStringyFy',JSON.stringify(this.optFormData));
  38.  
  39.         const data = {
  40.             optDataFyObj: this.optFormData,           
  41.         };
  42.  
  43.         console.log('optDataFyObj## ',JSON.stringify(data));
  44.  
  45.         if(flag){
  46.             const result = await submitOptRecord({                
  47.                 jsonDataStr: JSON.stringify(data)
  48.  
  49.             });
  50.             console.log('result## ' , result);
  51.  
  52.             const toastEvent = new ShowToastEvent({
  53.                 title:'success',
  54.                 message:'Record created successfully',
  55.                 variant:'success'
  56.                });
  57.                this.dispatchEvent(toastEvent);
  58.                this.spinnerStatus=false;
  59.  
  60.             if (result.status == 200) {
  61.  
  62.                 // naviagte to record page
  63.                 this.navigateToRecordPage(this.opportunityId);
  64.  
  65.             } else {
  66.                 return this.setFormError(result.message);
  67.             }
  68.  
  69.         }
  70.  
  71.     }
  72.  
  73.     navigateToRecordPage(recordId) {
  74.         this[NavigationMixin.GenerateUrl]({
  75.             type: 'standard__recordPage',
  76.             attributes: {
  77.                 recordId: recordId,
  78.                 actionName: 'view',
  79.             },
  80.         }).then(url => {
  81.             window.location.href = url;
  82.         });
  83.     }
  84.  
  85. }

 

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]

  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__HomePage</target>
  8.         <target>lightning__RecordPage</target>
  9.         <target>lightning__RecordAction</target>
  10.         <target>lightning__UtilityBar</target>
  11.         <target>lightning__Tab</target>
  12.     </targets>
  13.     <targetConfigs>
  14.         <targetConfig targets="lightning__RecordAction">
  15.             <actionType>ScreenAction</actionType>
  16.         </targetConfig>
  17.     </targetConfigs>
  18. </LightningComponentBundle>

 

Create Apex Class Controller

Step 4:- Create Apex Class : createOptCtrl.cls

From Developer Console >> File >> New >> Apex Class

createOptCtrl.cls [Apex Class Controller]

  1.     public WITH sharing class createOptCtrl {
  2.  
  3.     @AuraEnabled
  4.     public static Map<String, Object> submitOptRecord(String jsonDataStr) {
  5.         Map<String, Object> RESULT = NEW Map<String, Object>();
  6.         try {
  7.             Map<String, Object> formDataMap = (Map<String, Object>)JSON.deserializeUntyped(jsonDataStr);
  8.             System.debug('formDataMap ' + formDataMap);
  9.             Map<String, Object> OptDataMap = (Map<String, Object>)formDataMap.get('optDataFyObj');
  10.  
  11.             Opportunity optObj = NEW Opportunity();
  12.             optObj.Name = getStringValueFromMap(OptDataMap, 'Name');
  13.             optObj.CloseDate = getDateValueFromMap(OptDataMap, 'CloseDate');
  14.             optObj.StageName = getStringValueFromMap(OptDataMap, 'StageName');
  15.             optObj.TotalOpportunityQuantity = getIntValueFromMap(OptDataMap, 'TotalOpportunityQuantity');
  16.             optObj.Amount = getDecimalValueFromMap(OptDataMap, 'Amount');
  17.  
  18.             system.debug('optObj### ' + optObj);
  19.             List<DATABASE.SaveResult> insertResult = DATABASE.insert(NEW List<Opportunity>{optObj});
  20.             System.debug('insertResult ' + insertResult);
  21.  
  22.         }catch(Exception ex) {
  23.             System.debug('Exception ' + ex.getMessage() + ',line' + ex.getLineNumber());
  24.             RESULT.put('status', 500);
  25.             RESULT.put('message', 'Exception ' + ex.getMessage() + ',line' + ex.getLineNumber());
  26.         }
  27.         RETURN RESULT;
  28.  
  29.     }
  30.  
  31.  
  32.  
  33.  
  34.     public static String getStringValueFromMap(Map<String, Object> dataMap, String fieldName) {
  35.         String VALUE;
  36.         try {
  37.             IF(dataMap.containsKey(fieldName)) {
  38.                 VALUE = String.valueOf(dataMap.get(fieldName));
  39.             }
  40.  
  41.             VALUE = String.isEmpty(VALUE) ? VALUE :  String.valueOf(VALUE);
  42.         } catch(Exception ex) {
  43.             System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  44.         }
  45.  
  46.         RETURN VALUE;
  47.     }
  48.  
  49.  
  50.  
  51.     public static DATE getDateValueFromMap(Map<String, Object> dataMap, String fieldName) {
  52.         DATE VALUE;
  53.         try {
  54.             String str;
  55.             IF(dataMap.containsKey(fieldName)) {
  56.                 str = String.valueOf(dataMap.get(fieldName));
  57.             }
  58.  
  59.             VALUE = String.isEmpty(str) ? VALUE :  DATE.valueOf(str);
  60.         } catch(Exception ex) {
  61.             System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  62.         }
  63.  
  64.         RETURN VALUE;
  65.     }
  66.  
  67.  
  68.     public static INTEGER getIntValueFromMap(Map<String, Object> dataMap, String fieldName) {
  69.         INTEGER VALUE;
  70.         try {
  71.             String str;
  72.             IF(dataMap.containsKey(fieldName)) {
  73.                 str = String.valueOf(dataMap.get(fieldName));
  74.             }
  75.  
  76.             VALUE = String.isEmpty(str) ? VALUE :  INTEGER.valueOf(str);
  77.         } catch(Exception ex) {
  78.             System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  79.         }
  80.  
  81.         RETURN VALUE;
  82.     }
  83.  
  84.  
  85.     public static DECIMAL getDecimalValueFromMap(Map<String, Object> dataMap, String fieldName) {
  86.         DECIMAL VALUE;
  87.         try {
  88.             String str;
  89.             IF(dataMap.containsKey(fieldName)) {
  90.                 str = String.valueOf(dataMap.get(fieldName));
  91.             }
  92.  
  93.             VALUE = String.isEmpty(str) ? VALUE :  DECIMAL.valueOf(str);
  94.         } catch(Exception ex) {
  95.             System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  96.         }
  97.  
  98.         RETURN VALUE;
  99.     }
  100.  
  101.  
  102.  
  103.  
  104. }

 

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

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

 
   
 
 

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