ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

Create Lightning Charts With Chart.Js

Home / Article & Blogs / Apex / Create Lightning Charts With Chart.Js
By Team ABSYZ inApex, Lightning, Salesforce

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

chart.jsLightning component
100
Like this post
127 Posts
Team ABSYZ

Search Posts

Archives

Categories

Recent posts

All About The OmniStudio FlexCards

All About The OmniStudio FlexCards

Boost Customer Experience With Repeater Widget in CRM Analytics

Boost Customer Experience With Repeater Widget in CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics

Net zero as a Service In CPG Industry

Net zero as a Service In CPG Industry

How Do We Import an External Library into Salesforce Lightning?

How Do We Import an External Library into Salesforce Lightning?

  • Previous PostAutomate metadata backup of your Salesforce org with the help of ANT and GIT
  • Next PostSalesforce Summer'17 Release: Platform Events

Related Posts

All About The OmniStudio FlexCards
OmniStudio Salesforce

All About The OmniStudio FlexCards

Boost Customer Experience With Repeater Widget in CRM Analytics
CRM Analytics Salesforce

Boost Customer Experience With Repeater Widget in CRM Analytics

Enhance Insights Using Custom Tooltips In CRM Analytics
CRM Analytics Salesforce

Enhance Insights Using Custom Tooltips In CRM Analytics

How Do We Import an External Library into Salesforce Lightning?
Lightning Salesforce

How Do We Import an External Library into Salesforce Lightning?

12 Comments

  1. skhilauria1988
    Reply
    17 July 2017

    Nicely Done ! Great Info 🙂

    Reply
    • Jay Rizzi (@jayrizzi1)
      Reply
      3 August 2017

      quick question, how can you implement a loading spinner if your data is being brought in by say an API call?

      Reply
      • pradeepkumar batta
        Reply
        4 August 2017

        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.

        Reply
    • Narsimha Rao
      Reply
      25 July 2018

      Great Stuff! Although I’m unable to display the chart when the component is wrapped in a VF Page and hosted on Classic. Any suggestions?

      Thanks
      Narsimha Rao

      Reply
  2. Abhi Tripathi
    Reply
    24 July 2017

    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 ?

    Reply
    • pradeepkumar batta
      Reply
      25 July 2017

      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.

      Reply
  3. Pooja
    Reply
    14 March 2018

    Tried using this but getting Failed to create chart: can’t acquire context from the given item

    Reply
    • Pooja
      Reply
      15 March 2018

      Got this fixed, somehow I had to delete the whole component and recreated and it worked!

      Reply
      • pradeepkumar batta
        Reply
        15 March 2018

        Hi Pooja,

        Fine!!!!!

        Regards,
        Pradeepkumar Batta

        Reply
      • Chidanand
        Reply
        3 May 2018

        Hi, I am also getting the same error. Could you please give me some hint to fix it?

        Reply
  4. Generating Charts Using Lightning Components – Pritam Shekhawat
    Reply
    15 May 2018
    Reply
  5. Ganesh Ekhande
    Reply
    13 September 2018

    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!

    Reply

Leave a Reply (Cancel reply)

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

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT