Create Lightning Charts With Chart.Js

Create Lightning Charts With Chart.Js

Everyone loves a smooth and slick UI. And what if, if you have an awesome UI for which you have to design once and will work across the devices, which is nothing but responsive. One such library which was great but not supported in Lightning experience was Chart.js. As some of its external libraries had older versions, Chart.js wasn’t supported in Lightning Locker Service. Oh, wait a min, what is a Locker Service? That itself is a story to tell about for another day. Anyways you can check out the documentation here (Lightning locker service).

But that is not the situation now. Due to the latest version updates of Chart.js, it is finally compatible with Lightning Locker Service. You may be wondering how can I implement Chart.js in my org? Well, through this blog post am going to explain how to build a Generic Chart.js Lightning component and by the end of it you will be able to show off awesome, responsive and eye-candy charts to your peers.

I have created a generic component which will work for all the SObjects with the configuration on component level. You can use this component anywhere.

Here I have used a design component to configure any Object and it’s picklist field which will be used in the calculation and displayed on the chart.

First, we need to create a static resource with chart.js latest file and include the static resource in the component. You can download the Chart.js file from here Download.

[sourcecode language=”Java”]

<ltng:require scripts=”{!$Resource.Chart_bundle_min_js}”>

[/sourcecode]

We can define which type of chart we want to display. Chart colours always keep changing when we refresh the page.

This is the javascript code I have used for dynamic colours.

[sourcecode language=”java”]

getRandomColor : function(component) {
var letters = ‘0123456789ABCDEF’;
var color = ‘#’;
for (var i = 0; i &lt; 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

[/sourcecode]

Here is the method to retrieve records:

[sourcecode language=”java”]
// Method to query the data from SObject
@AuraEnabled
public static List<wrapperclass> generateDataa(String selectedObject, String selectedfield) {
String QueryStr = queryAllFrom(selectedObject);
List<Sobject> groupedResults = Database.query(QueryStr); // Retrive the records from selected object
List<wrapperclass> lstofwrapperclass = new List<wrapperclass> (); // Wrapper calss to hold records with selected field value
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe(); // Describing the SObjects
Map<string, string> Mapofpicklist = new Map<string, string> ();
List<String> options = new List<String> ();
Schema.sObjectType sobjecttype = schemaMap.get(selectedObject); // Get SObject type
Schema.DescribeSObjectResult sobjectdescribe = sobjecttype.getDescribe(); // Describing the selected SObjects
Map<String, Schema.SObjectField> fieldmap = sobjectdescribe.fields.getMap(); // Holding SObject fields
for (Sobject sobj: groupedResults) {
for (Schema.SObjectField field: fieldMap.values()) {
if (string.valueof(field) == selectedfield) { // Checking the selected field
Schema.DescribeFieldResult fieldResult = field.getDescribe();
wrapperclass wrap = new wrapperclass();
wrap.selectedfield = String.valueof(sobj.get(fieldResult.getName())); // Assigning the selected field value of a record
wrap.lstofobj = sobj; // Assigning selected SObject record
lstofwrapperclass.add(wrap);
}
}
}
return lstofwrapperclass; // return the wrapper with records and selected field value
}
[/sourcecode]

This is where we have to configure the component and mention the API Name of the Object and it’s Field and also type of chart.

pic1

Final output of the component will be like this.

pic2

Note: My component supports bar, pie, doughnut charts. You can modify the Lightning controller for supporting more different charts.

References: View Code In Github

12 thoughts on “Create Lightning Charts With Chart.Js”

      1. pradeepkumar batta

        Hi Jay,

        I haven’t implemented the spinner, if you want to implement spinner in component, modify the component and add spinner code and show the spinner when you make a call and hide the same when you get the response from server.

  1. Abhi Tripathi

    Nice post, the way you make the way of using Salesforce data in the charts is incredible.
    I’ve a question in the helper I see three functions displaydata, helperMethod, getRandomColor all these three method are nowhere used, can you please explain why ?
    And if you are using them and then where ? in Charts.JS CDN ?

    1. pradeepkumar batta

      Hi Abhi,

      Thanks for knowing something!!
      “getRandomColor” is used in inside “helpermethod”, “helpermethod” is used inside “displaydata” and “displaydata” function is used in inside the controller. If you see the code in GitHub you can easily understand the way I hook up.

  2. Pingback: Generating Charts Using Lightning Components – Pritam Shekhawat

  3. Great Stuff! Does chart work if data is brought by Asynchronous API Callout(Continuation)? Visualforce Apex Chart does not show updated data brought by Asynchronous Callout. Thanks!

Leave a Comment

Your email address will not be published. Required fields are marked *

Recent Posts

salesforce world tour essentials mumbai
Salesforce World Tour Essentials Mumbai (19 June, 2024)
benefits of using salesforce for higher education Industry
Benefits Of Using Salesforce For Higher Education Industry?
salesforce for real estate
Salesforce for Real Estate: How Salesforce CRM Can Help Realtors
salesforce consumer goods cloud store setup
A Detailed Look into Salesforce Consumer Goods Cloud Store Setup
salesforce revenue cloud does your business need it
Salesforce Revenue Cloud: Does Your Business Need It?
Scroll to Top