Friday, September 3, 2021

How to Read and Display Quote Line Items from a given Quote Record

 AIM: I want to read all quote line item records from a quote record using lightning web component.

Below is lightning web component which is taking quite Id as parameter to read quote line items

downLoadQuoteLineItems.html

<template>
<lightning-card title="Export Data as CSV in Lightning Web Components" icon-name="custom:custom16">
        <template if:true={data}>
            <div class="slds-p-around_medium lgc-bg-inverse">
                <p>download data as a CSV format, Click Here &nbsp;
                    <lightning-button icon-name="utility:download" 
                                      label="Download as CSV" 
                                      title="Download CSV File"
                                      onclick={downloadCSVFile} variant="brand"></lightning-button>
                </p>
            </div>
            <div class="slds-m-around_medium">
                <!-- Datatable component -->
                    <lightning-datatable columns={columns} 
                                         data={data} 
                                         hide-checkbox-column="true"
                                         key-field="id"></lightning-datatable>
            
            </div>
        </template>
    </lightning-card>
</template>

DownLoadQuoteLineItems.js

import { LightningElement, track, api, wire} from 'lwc';
import getQutelineItemlist from '@salesforce/apex/AccountCreate.getQuoteLineItems';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
const cols = [
    {label: 'Id',fieldName: 'Id'}, 
    {label: 'LineNumber',fieldName: 'LineNumber'},
    {label: 'QuoteId',fieldName: 'QuoteId'}, 
    {label: 'Quantity',fieldName: 'Quantity',type: 'number'}, 
    {label: 'UnitPrice',fieldName: 'UnitPrice', type: 'number'}, 
    {label: 'Discount',fieldName: 'Discount', type: 'number'}, 
{label: 'ServiceDate',fieldName: 'ServiceDate', type: 'date'}, 
{label: 'ListPrice',fieldName: 'ListPrice', type: 'number'},
{label: 'TotalPrice',fieldName: 'TotalPrice', type: 'number'},
];
export default class DownLoadQuoteLineItems extends LightningElement {
@api recordId;
    @track error;
    @track data;
    @track columns = cols;
  @wire(getQutelineItemlist, {quoteId: '$recordId'})
  wiregetquotelineitems({data, error}){
if(data){
this.data = data;
this.error = undefined;
}else if(error){
this.error = error;
                     this.dispatchEvent(
                     new ShowToastEvent({
                        title: 'Error while getting Quote Line Items', 
                        message: error.message, 
                        variant: 'error'
                    }),
            );
            this.data = undefined;
}
  }
    downloadCSVFile() {   
        let rowEnd = '\n';
        let csvString = '';
        let rowData = new Set();
        // getting keys from data
        this.data.forEach(function (record) {
            Object.keys(record).forEach(function (key) {
                rowData.add(key);
            });
        });
        rowData = Array.from(rowData);
        csvString += rowData.join(',');
        csvString += rowEnd;
        for(let i=0; i < this.data.length; i++){
            let colValue = 0;
            for(let key in rowData) {
                if(rowData.hasOwnProperty(key)) {
                    let rowKey = rowData[key];
                    if(colValue > 0){
                        csvString += ',';
                    }
                    let value = this.data[i][rowKey] === undefined ? '' : this.data[i][rowKey];
                    csvString += '"'+ value +'"';
                    colValue++;
                }
            }
            csvString += rowEnd;
        }
        // Creating anchor element to download
        let downloadElement = document.createElement('a');
        // This  encodeURI encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
        downloadElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvString);
        downloadElement.target = '_self';
        // CSV File Name
        downloadElement.download = 'QuoteLineItem Data.csv';
        // below statement is required if you are using firefox browser
        document.body.appendChild(downloadElement);
        // click() Javascript function to download CSV file
        downloadElement.click(); 
    }
}

DownLoadQuoteLineItems.js-meta.xml

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>50</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>

Apex class

public class AccountCreate {
@AuraEnabled(Cacheable = true)
    public static List<QuoteLineItem> getQuoteLineItems(String quoteId){
      return [select Id, LineNumber, QuoteId, Quantity, UnitPrice, Discount, ServiceDate, ListPrice, TotalPrice from QuoteLineItem where QuoteId =:quoteId];
    }
}