Display Bar Chart

Learn How to Display Bar Chart in Salesforce Lightning Web Component

Introduction

The graphical representation of information and data is known as data visualization. Data visualisation tools make it easy to see and understand trends, outliers, and patterns in data by using visual elements including charts, graphs, and maps. Any company's executives and managers want to see their data visualized in a way that gives them insights.

ChartJS is one such visualization library that is both common and open source. For designers and developers, it's an easy but versatile JavaScript charting. Let's look at how we can use ChartJs to draw charts on a lightning web component in this article.

In this blog, I'll show you how to use apex to get data from a Salesforce object and feed it into a bar chart. In addition, an aggregate query will be used to summarise the data, and the data will be presented in two datasets. I used two LWCs to build the UI. One is a parent, while the other is a child component.

The parent component will handle most of the data processing and transfer an attribute (chartConfiguration) to the child component. We're attempting to illustrate an Opportunity Bar Chart with Estimated Revenue & Sum for different stages in this article.

Prerequisite to be followed before starting the process

Download the ChartJS file here and save it as a static resource called "ChartJS."

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js

Create a Lightning Web Component named childbarchart and paste the code below into it.

dont miss out iconDon't forget to check out: 5 Groundbreaking Features Exclusive to Salesforce Lightning Experience

childbarchart.html

<template>
    <div class="slds-p-around_small slds-grid slds-grid--vertical-align-center slds-grid--align-center">
        <canvas class="barChart" lwc:dom="manual"></canvas>
        <div if:false={isChartJsInitialized} class="slds-col--padded slds-size--1-of-1">
            <lightning-spinner alternative-text="Loading" size="medium" variant="base"></lightning-spinner>
        </div>
    </div>
</template>

childbarchart.js

import { LightningElement, api } from 'lwc';
import chartjs from '@salesforce/resourceUrl/ChartJs';
import { loadScript } from 'lightning/platformResourceLoader';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'; 
export default class childbarchart extends LightningElement {
    @api chartConfig; 
    isChartJsInitialized;
    renderedCallback() {
        if (this.isChartJsInitialized) {
            return;
        }
        // load chartjs from the static resource
        Promise.all([loadScript(this, chartjs)])
        .then(() => {
            this.isChartJsInitialized = true;
            const ctx = this.template.querySelector('canvas.barChart').getContext('2d');
            this.chart = new window.Chart(ctx, JSON.parse(JSON.stringify(this.chartConfig)));
        })
        .catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading Chart',
                    message: error.message,
                    variant: 'error',
                })
            );
        });
    }
}

BarChartController.cls

public class BarChartController {
    @AuraEnabled(cacheable=true)
    public static List<AggregateResult> getOpportunities(){
        return [SELECT SUM(ExpectedRevenue) expectRevenue, SUM(Amount) amount, StageName stage 
        FROM Opportunity WHERE StageName NOT IN ('Closed Won') GROUP BY StageName LIMIT 20];
    }
}

Create a new LWC as the parentComponent that will handle all of the data entry for us.

ParentBarchart.html

<template>
    <lightning-card title="Open Opportunities" icon-name="utility:chart">
        <template if:true={chartConfiguration}>
            <c-child-bar-chart chart-config={chartConfiguration}></c-child-bar-chart>
        </template>
    </lightning-card>
</template>

ParentBarchart.js

import { LightningElement, wire } from 'lwc';
import getOpportunities from '@salesforce/apex/BarChartController.getOpportunities'; 
export default class ParentBarchart extends LightningElement {
    chartConfiguration;
    @wire(getOpportunities)
    getOpportunities({ error, data }) {
        if (error) {
            this.error = error;
            this.chartConfiguration = undefined;
        } else if (data) {
            let chartAmtData = [];
            let chartRevData = [];
            let chartLabel = [];
            data.forEach(opp => {
                chartAmtData.push(opp.amount);
                chartRevData.push(opp.expectRevenue);
                chartLabel.push(opp.stage);
            });
            this.chartConfiguration = {
                type: 'bar',
                data: {
                    datasets: [{
                        label: 'Amount',
                        backgroundColor: "green",
                        data: chartAmtData,
                    },{
                        label: 'Expected Revenue',
                        backgroundColor: "orange",
                        data: chartRevData,
                    },],
                    labels: chartLabel,
                },
                options: {},
            };
            console.log('data => ', data);
            this.error = undefined;
        }
    }
}

dont miss out iconCheck out another amazing blog by Anuj here: Best Practices To Be Followed In Salesforce Lightning Web Components

ParentBarchart.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
        <target>lightning__AppPage</target>
    <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Responses

  1. When adding LWC to a tab I get the error.

    Validation Errors While Saving Record(s)
    There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "We couldn't validate your component c:parentBarchart used in Custom Tab. Review it and try again.".

    Do you know the solution?
    Sorry for my English, thanks.

Popular Salesforce Blogs

AI in Salesforce

Transform businesses with the power of Artificial Intelligence leveraged through Salesforce Einstein

Blog in

Artificial Intelligence is powering next-generation customer experiences with smart predictions, intelligent recommendations, timely automation and much more. Gartner predicts that by 2020, a staggering 85% of…