vijayk3327 / LWC

1 stars 0 forks source link

How to Create Quote and QuoteLineItem From Opportunity in Lightning Web Component – LWC Salesforce #94

Open vijayk3327 opened 1 year ago

vijayk3327 commented 1 year ago

In this post we are going to learn about How to Create Quote and QuoteLineItem From Opportunity in Lightning Web Component – LWC Salesforce.

Quote Line Items are automatically created when the Quote is created from an Opportunity based on the Opportunity Products attached to that Opportunity. Creating a Quote from an Opportunity in Classic always results in Quote Line Items created but in Lightning for the same record it is possible that no Quote Line Items are created. To know more about Quote and QuoteLineItem, Click Here.

👉 To get source code live demo link, Click Here.

Create Lightning Web Component HTML Step 1:- Create Lightning Web Component : createQuoteAndLineItemLwc.html

``

Create Lightning Web Component JavaScript Step 2:- Create Lightning Web Component : createQuoteAndLineItemLwc.js

`import { LightningElement, track,api, wire } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; import submitOptRecord from '@salesforce/apex/createQuoteAndLineItemLwcCtrl.submitOptRecord'; import getOpportunityList from '@salesforce/apex/createQuoteAndLineItemLwcCtrl.getOpportunityList'; import saveQuoteLineItem from '@salesforce/apex/createQuoteAndLineItemLwcCtrl.saveQuoteLineItem';

//import NAME_FIELD from '@salesforce/schema/QuoteLineItem.Name'; import Description_FIELD from '@salesforce/schema/QuoteLineItem.Description'; import UnitPrice_FIELD from '@salesforce/schema/QuoteLineItem.UnitPrice'; import Quantity_FIELD from '@salesforce/schema/QuoteLineItem.Quantity'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import {NavigationMixin} from 'lightning/navigation';

export default class CreateQuoteAndLineItemLwc extends NavigationMixin(LightningElement) {

@track quoteLineItemList = []; 

@track index = 0;
@api recordId;    
@api quoteRecId;

// @track name = NAME_FIELD; @track Description = Description_FIELD; @track UnitPrice = UnitPrice_FIELD; @track Quantity = Quantity_FIELD; @track quoteLineRecoreId; @track message; @track error; isLoaded = false;

@track optItemList ;
@track oppProductLineItemArr=[];
@track optFormData = {};
@track Product2Id= '01t5g000003OxvQAAS';
@track PricebookEntryId='01u5g000003gfcsAAA';
@track Pricebook2Id='01s5g00000KmN13AAF';

    //Start ConnectedCallback

    connectedCallback() {

    }

    @wire(getOpportunityList,{recId:'$recordId'})
    getInfos({error,data}){
    if(error){
        console.log('error == '+JSON.stringify(error));
    }else if(data){
        console.log('data == ', JSON.stringify(data));
        this.oppProductLineItemArr = JSON.parse(JSON.stringify(data));

      return;

    }
}

//Start Quote

//Start Quote Line Item // acc qotLine = { Name : this.name,
Description : this.Description,
UnitPrice : this.UnitPrice, Quantity : this.Quantity, QuoteId : '', Product2Id :this.Product2Id,
PricebookEntryId :this.PricebookEntryId, key : '' }

addRow(){

    this.index++;

    var i = this.index;

    this.qotLine.key = i;
    this.quoteLineItemList.push(JSON.parse(JSON.stringify(this.qotLine)));

    console.log('Enter ',this.quoteLineItemList);

}

removeRow(event){
    this.isLoaded = true;
    var selectedRow = event.currentTarget;
    var key = selectedRow.dataset.id;
    if(this.quoteLineItemList.length>1){
        this.quoteLineItemList.splice(key, 1);
        this.index--;
        this.isLoaded = false;
    }else if(this.quoteLineItemList.length == 1){
        this.quoteLineItemList = [];
        this.index = 0;
        this.isLoaded = false;
    }

} 

handleNameChange(event) {
    var selectedRow = event.currentTarget;
    console.log('selectedRow_! ' + selectedRow );
    var key = selectedRow.dataset.id;
    var accountVar = this.quoteLineItemList[key];
    this.quoteLineItemList[key].Name = event.target.value;
  console.log('handleNameChange# ' + this.quoteLineItemList[key].Name);
}

handleDescriptionChange(event) {
    var selectedRow = event.currentTarget;
    var key = selectedRow.dataset.id;
    var lineItemVar = this.quoteLineItemList[key];
    this.quoteLineItemList[key].Description = event.target.value;
}

handleUnitPriceChange(event) {
    var selectedRow = event.currentTarget;
    var key = selectedRow.dataset.id;
    var lineItemVar = this.quoteLineItemList[key];
    this.quoteLineItemList[key].UnitPrice = event.target.value;
}

handleQuantityChange(event) {
    var selectedRow = event.currentTarget;
    var key = selectedRow.dataset.id;
    var lineItemVar = this.quoteLineItemList[key];
    this.quoteLineItemList[key].Quantity = event.target.value;
}

//Start Quote Javascript

//Start Quote and Quote Lline Item Save Functionality 
saveRecord(){        

  //Start Quote  

    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, 

    };

    console.log('optDataFyObj## ',JSON.stringify(data));

    //if(flag){
        const result = submitOptRecord({
            jsonDataStr: JSON.stringify(data)
        })
        .then(result => {
            //resultData1 =JSON.stringify(result);
            console.log('result1' , JSON.parse(result));
           // console.log('result1_A' , result);
            this.quoteJsonData = result[0].Id;
            console.log('quoteJsonData' , this.quoteJsonData);
            console.log('result2', result[0].id);
            var quoteId;
            var obj = JSON.parse(result, function (key, value) {
                if(key == 'id' && value != undefined &&  value != null) {
                console.log('Quote id '+ key+'   :: '+value);
                quoteId = value;

                }

              });

             console.log('quoteId 175 #' + quoteId );
              this.quoteRecId=quoteId;

              for(let i of this.quoteLineItemList){

               i['QuoteId'] =quoteId;
              i['Name'] =quoteId;

                console.log('aaa Item_' + JSON.stringify(i)); 

              }

               console.log('quoteLineItemListQQ ' + this.quoteLineItemList);
              //Start Qoute Line Item 
                    saveQuoteLineItem({quoteItemList : this.quoteLineItemList})
                    .then(result => {
                        console.log('result_11' , JSON.parse(result));
                        this.quoteLineRecoreId = result.Id;
                        console.log('resultId ' + result[0].Id);
                        console.log('quoteLineRecoreId@@@ ' + this.quoteLineRecoreId);
                        this.message = result;
                        this.error = undefined;

                    })
                    .catch(error => {
                        this.message = undefined;
                        this.error = error;                            
                        console.log("error", JSON.stringify(this.error));
                    });

                    //End Qoute Line Item 

                   //Start Toast Message 
                    const toastEvent = new ShowToastEvent({
                        title:'Success!',
                        message:'Record created successfully',
                        variant:'success'
                      });
                      this.dispatchEvent(toastEvent);

                      //End Toast Message

                    /*Start Navigation*/
                    this[NavigationMixin.Navigate]({
                        type: 'standard__recordPage',
                        attributes: {
                            recordId: quoteId,
                            objectApiName: 'Quote',
                            actionName: 'view'
                        },
                    });
                    /*End Navigation*/ 

        });
    //}

  //End Quote

}

}`

Create Lightning Web Component Meta XML Step 3:- Create Lightning Web Component : createQuoteAndLineItemLwc.js-meta.xml

`<?xml version="1.0" encoding="UTF-8"?>

56.0 true lightning__AppPage lightning__HomePage lightning__RecordPage lightning__RecordAction lightning__UtilityBar ` **Create Apex Class Controller Step 4:- Create Apex Controller : insertLookupFieldValueLwcCtrl.cls** `public WITH sharing class createQuoteAndLineItemLwcCtrl { public createQuoteAndLineItemLwcCtrl() { } @AuraEnabled(cacheable=TRUE) public static List getOpportunityList(Id recId){ List optList = [SELECT Id, Name, Description FROM Opportunity WHERE Id=:recId]; RETURN optList; } //START Quote @AuraEnabled public static String submitOptRecord(String jsonDataStr) { Map RESULT = NEW Map(); String DataRespoce =''; try { Map formDataMap = (Map)JSON.deserializeUntyped(jsonDataStr); Map OptDataMap = (Map)formDataMap.get('optDataFyObj'); // Opportunity optObj = NEW Opportunity(); Quote optObj = NEW Quote(); optObj.Name = getStringValueFromMap(OptDataMap, 'Name'); optObj.OpportunityId = getStringValueFromMap(OptDataMap, 'OpportunityId'); optObj.Description = getStringValueFromMap(OptDataMap, 'Description'); optObj.Pricebook2Id = getStringValueFromMap(OptDataMap, 'Pricebook2Id'); List insertResult = DATABASE.insert(NEW List{optObj}); DataRespoce =JSON.serialize(insertResult); }catch(Exception ex) { RESULT.put('status', 500); RESULT.put('message', 'Exception ' + ex.getMessage() + ',line' + ex.getLineNumber()); } RETURN DataRespoce; } public static String getStringValueFromMap(Map 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 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; } //START Quote Line Item @AuraEnabled public static void saveQuoteLineItem(List quoteItemList){ try { INSERT quoteItemList; System.debug('quoteItemList## ' + quoteItemList); } catch(Exception ex) { System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber()); } } //END Quote Line Item }` **[👉 To get source code live demo link, Click Here.](https://www.w3web.net/create-quote-and-quotelineitem-from-opportunity/)**
rob69nex commented 8 months ago

Very Interested. How can download?