Skip to content

Instantly share code, notes, and snippets.

@Sunil02kumar
Last active January 30, 2018 02:56
Show Gist options
  • Save Sunil02kumar/2b80d17b7871637a3561b8a62f19d666 to your computer and use it in GitHub Desktop.
Save Sunil02kumar/2b80d17b7871637a3561b8a62f19d666 to your computer and use it in GitHub Desktop.
Using Chartjs in Lightning Components
<aura:component controller="SK_ChartJsCmpController">
<aura:attribute name="ltngChartData" type="Object"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="slds-grid slds-wrap">
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" >
<div class="slds-card__body slds-card__body_inner" aura:id="lineChartSection"/>
</div>
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" >
<div class="slds-card__body slds-card__body_inner" aura:id="horrizontalBarChartSection"/>
</div>
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" >
<div class="slds-card__body slds-card__body_inner" aura:id="pieChartSection"/>
</div>
</div>
</aura:component>
<aura:application extends="force:slds">
<c:SK_ChartJsCmp />
</aura:application>
public class SK_ChartJsCmpController {
public static List<string> bgColorCodesForChart = new List<string>{'#FF6384','#36A2EB','#bed2ce','#0abc70','#f5b022','#e85e7f'};
@AuraEnabled
public static ChartDataWrapper findDataSetForChart(){
ChartDataWrapper cdataSet = new ChartDataWrapper();
string queryString = 'SELECT ForecastCategoryName, SUM(Amount) FROM Opportunity GROUP BY ForecastCategoryName ';
AggregateResult[] groupedResults = database.query(queryString);
integer count =0;
for (AggregateResult ar : groupedResults)
{
string clabel = string.valueof(ar.get('ForecastCategoryName'));
string categorylabel = string.valueof(ar.get('ForecastCategoryName'));
decimal amount = (decimal)ar.get('expr0');
amount = amount != null ? (amount/1000000).setScale(2) : 0;
cdataSet.labels.add(clabel + '('+string.valueof(amount)+')');
cdataSet.dataValues.add(string.valueof(amount));
if(bgColorCodesForChart[count] != null){
cdataSet.bgColorValues.add(bgColorCodesForChart[count]);
count++;
}
System.debug('ForecastCategoryName:' + clabel);
System.debug('Sum amount' + string.valueof(amount));
}
return cdataSet;
}
public class ChartDataWrapper{
@AuraEnabled
public list<string> labels{get;set;}
@AuraEnabled
public list<string> dataValues{get;set;}
@AuraEnabled
public list<string> bgColorValues{get;set;}
public ChartDataWrapper(){
labels =new list<string> ();
dataValues = new list<string> ();
bgColorValues = new list<string> ();
}
}
}
({
doInit : function(component, event, helper) {
var params ={};
helper.callToServer(
component,
"c.findDataSetForChart",
function(response)
{
console.log('apex response :'+JSON.stringify(response));
component.set("v.ltngChartData",response);
//display line chart
helper.generateChartData(component,"line","lineChartSection");
//display horrizontal bar chart
helper.generateChartData(component,"bar","horrizontalBarChartSection");
//display Pie chart
helper.generateChartData(component,"pie","pieChartSection");
},
params
);
}
})
({
callToServer : function(component, method, callback, params) {
console.log('Calling helper callToServer function');
var action = component.get(method);
if(params){
action.setParams(params);
}
console.log('****param to controller:'+JSON.stringify(params));
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
callback.call(this,response.getReturnValue());
}else if(state === "ERROR"){
alert('Problem with connection. Please try again.');
}
});
$A.enqueueAction(action);
},
loadChart : function(component, chartSection, componentName, params){
console.log('*****load chart called'+chartSection);
$A.createComponent(
componentName,
params,
function(chartBox) {
//Add the dynamic chart to div
if (component.isValid()) {
console.log('****creating the chart component');
var targetCmp = component.find(chartSection);
targetCmp.set("v.body",[]);
var body = targetCmp.get("v.body");
body.push(chartBox);
targetCmp.set("v.body", body);
}
}
);
},
generateChartData: function (component,chartType,chartDivSectionId){
var cDatask = component.get("v.ltngChartData");
var cmpAttributes = {
ltngChartData: cDatask,
ltngChartType :chartType
}
if(cDatask.labels){
this.loadChart(
component,
chartDivSectionId,
"c:SK_ChartJsTemplate",
cmpAttributes
);
}
}
})
<aura:component >
<ltng:require scripts="{!$Resource.SK_Chartjs}" afterScriptsLoaded="{!c.generateChart}"/>
<aura:attribute name="ltngChartData" type="object"/>
<aura:attribute name="ltngChartType" type="String" default="pie"/>
<div class="slds-grid slds-wrap">
<div class="slds-size--1-of-1 slds-medium-size--1-of-1 slds-large-size--1-of-1" >
<canvas aura:id="chartdiv" ></canvas>
</div>
</div>
</aura:component>
({
generateChart : function(component, event, helper) {
//for bar chart
var pieChartData = component.get("v.ltngChartData");
var chartLabel = component.get("v.ltngChartType") + ':Opportunities Grouped By Forcast Category';
var cdata = {
labels: pieChartData.labels,
datasets: [
{
label:chartLabel,
data: pieChartData.dataValues,
backgroundColor: pieChartData.bgColorValues,
borderColor:'rgba(62, 159, 222, 1)',
fill: false,
pointBackgroundColor: "#FFFFFF",
pointBorderWidth: 4,
pointHoverRadius: 5,
pointRadius: 3,
bezierCurve: true,
pointHitRadius: 10
}
]
}
//Get the context of the canvas element we want to select
var ctx1 = component.find("chartdiv").getElement();
var lineChart = new Chart(ctx1 ,{
type: component.get("v.ltngChartType"),
data: cdata,
options: {
legend: {
position: 'bottom'
},
responsive: true,
maintainAspectRatio: false
}
});
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment