https://sfdclesson.com/2019/09/04/report-chart-lightning-component-chart-js/
Below is the full code of ReportChart lightning component. Hope this will help many! 🙂
ReportChartCmp:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<aura:component controller="ReportChartCntrl" implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" > | |
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/> | |
<!-- load chart js library from static resource--> | |
<ltng:require scripts="/resource/Chart_Js/Chart.js-2.1.6/dist/Chart.bundle.js" /> | |
<aura:attribute name="reports" type="list"/> | |
<aura:attribute name="chartObj" type="object" access="public"/> | |
<aura:attribute name="isChartReady" type="Boolean" default="false"/> | |
<aura:attribute name="chartType" type="list"/> | |
<aura:handler event="aura:waiting" action="{!c.showSpinner}"/> | |
<aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/> | |
<aura:attribute name="Spinner" type="boolean" default="false"/> | |
<aura:attribute name="property1" type="string"/> | |
<aura:attribute name="selectedReport" type="string"/> | |
<aura:attribute name="selectedChartType" type="string"/> | |
<div class="slds"> | |
<div id="bodypart" style="background-color:white;"> | |
<aura:if isTrue="{!v.Spinner}"> | |
<div aura:id="spinnerId" class="slds-spinner_container"> | |
<div class="slds-spinner--brand slds-spinner slds-spinner--large slds-is-relative" role="alert"> | |
<span class="slds-assistive-text">Loading</span> | |
<div class="slds-spinner__dot-a"></div> | |
<div class="slds-spinner__dot-b"></div> | |
</div> | |
</div> | |
</aura:if> | |
<div class="slds-page-header"> | |
<lightning:icon iconName="utility:chart" alternativeText="Chart" size="small"/> | |
<b>MY CHART.JS</b> | |
</div> | |
<div class="slds-grid"> | |
<div class="slds-col slds-size--4-of-12 d1"> | |
<lightning:select aura:id="report" onchange="{!c.onSelectReportChange}" class="select" label="Select Report"> | |
<aura:iteration items="{!v.reports}" var="level"> | |
<option text="{!level.label}" value="{!level.value}" selected="{!level.selected}"/> | |
</aura:iteration> | |
</lightning:select> | |
</div> | |
<div class="slds-col slds-size--4-of-12"> | |
<lightning:select aura:id="type" onchange="{!c.onSelectChartTypeChange}" class="select" label="Select Chart Type"> | |
<aura:iteration items="{!v.chartType}" var="type"> | |
<option text="{!type.label}" value="{!type.value}" selected="{!type.selected}"/> | |
</aura:iteration> | |
</lightning:select> | |
</div> | |
<div class="slds-col slds-size--4-of-12"> | |
</div> | |
</div><br/> | |
<div aura:id="chartContainer" style=" "> | |
<canvas aura:id="myChart" id="{!v.property1}" /><!--reportChart--> | |
</div> | |
</div> | |
<div class="slds-page-header"> | |
<div class="slds-grid"> | |
<div class="slds-col slds-size--6-of-12"> | |
Powered By: <a href="https://www.chartjs.org/">ChartJS</a> | |
</div> | |
<div class="slds-col slds-size--3-of-12"> | |
</div> | |
<div class="slds-col slds-size--3-of-12"> | |
<b> <a href="https://sfdclesson.com/" target="_blank">SFDC LESSONS</a></b> | |
</div> | |
</div> | |
</div> | |
</div> | |
</aura:component> |
ChartJS CDN available at here or downloadÂ
ReportChartCmpController:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
doInit : function(component, event, helper) { | |
let action = component.get("c.fetchReportChartSettings"); | |
action.setCallback(this,function(response){ | |
let state = response.getState(); | |
if(state == 'SUCCESS'){ | |
let result = response.getReturnValue(); | |
console.log('Result: ' +result); | |
if(result.Report_Name__c!=null && result.Report_Name__c!=''){ | |
component.set("v.selectedReport",result.Report_Name__c); | |
} | |
if(result.Chart_Type__c!=null && result.Chart_Type__c!=''){ | |
component.set("v.selectedChartType",result.Chart_Type__c); | |
} | |
helper.getReports(component,event,helper); | |
} | |
else{ | |
if(response.getReturnValue()==null){ | |
helper.getReports(component,event,helper); | |
} | |
console.log('Something went wrong! '); | |
} | |
}); | |
$A.enqueueAction(action); | |
}, | |
onSelectReportChange : function(component, event, helper) { | |
component.set("v.isChartReady",true); | |
component.set("v.selectedReport",event.getSource().get("v.value")); | |
helper.CreateChart(component); | |
helper.updateSettings(component,event,helper); | |
}, | |
onSelectChartTypeChange : function(component, event, helper) { | |
component.set("v.isChartReady",true); | |
component.set("v.selectedChartType",event.getSource().get("v.value")); | |
helper.CreateChart(component); | |
helper.updateSettings(component,event,helper); | |
}, | |
showSpinner: function(component, event, helper) { | |
// make Spinner attribute true for display loading spinner | |
component.set("v.Spinner", true); | |
}, | |
// this function automatic call by aura:doneWaiting event | |
hideSpinner : function(component,event,helper){ | |
// make Spinner attribute to false for hide loading spinner | |
component.set("v.Spinner", false); | |
} | |
}) |
ReportChartCmpHelper:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
CreateChart : function(component) { | |
var chartType=component.get("v.selectedChartType").toLowerCase(); | |
if(chartType == 'polar area'){ | |
let values = chartType.split(" "); | |
let firstChar = values[0]; | |
let secondChar = values[1]; | |
chartType = firstChar+''+secondChar.charAt(0).toUpperCase() + secondChar.slice(1); | |
} | |
var action=component.get("c.getReportData"); | |
action.setParams({"reportName":component.get("v.selectedReport")}); | |
action.setCallback(this,function(response){ | |
var state=response.getState(); | |
if(state=='SUCCESS'){ | |
var reportResult = JSON.parse(response.getReturnValue()); | |
var data = []; | |
var Label= []; | |
if((reportResult.groupingsDown.groupings)!=null){ | |
for(var i=0; i < (reportResult.groupingsDown.groupings.length); i++){ | |
var tLabel = reportResult.groupingsDown.groupings[i].label; | |
Label.push(tLabel); | |
var tKey = reportResult.groupingsDown.groupings[i].key; | |
var tValue = reportResult.factMap[tKey + '!T'].aggregates[0].value; | |
data.push(tValue); | |
} | |
} | |
//Create chart | |
var el=component.find('myChart').getElement(); | |
var ctx=el.getContext('2d'); | |
if(window.bar!=undefined){ | |
window.bar.destroy(); | |
} | |
var background_color=new Array(); | |
for(var i=0 ; i<10 ; i++){ | |
var w,x,y,z; | |
w = parseInt(Math.random()*255); | |
x = parseInt(Math.random()*255); | |
y = parseInt(Math.random()*255); | |
z = Math.random(); | |
background_color.push('rgba('+w+','+x+','+y+','+z+')'); | |
} | |
window.bar = new Chart(ctx, { | |
type: chartType, | |
data: { | |
labels: Label, | |
datasets: [ | |
{ | |
label: "Data", | |
fillColor: background_color, | |
backgroundColor: background_color, | |
strokeColor: "rgba(220,220,220,1)", | |
data: data | |
} | |
] | |
}, | |
options: { | |
hover: { | |
mode: "none" | |
}, | |
scales: { | |
yAxes: [{ | |
ticks: { | |
beginAtZero:true | |
} | |
}] | |
} | |
} | |
}); | |
} | |
}); | |
$A.enqueueAction(action); | |
}, | |
loadSettings:function(component,event,helper){ | |
}, | |
getReports:function(component,event,helper){ | |
var chartTypeOption = ['Pie','Bar','Doughnut','Radar','Polar Area','Bubble']; | |
var action=component.get("c.fetchReports"); | |
action.setCallback(this,function(response){ | |
var state=response.getState(); | |
if(state=='SUCCESS'){ | |
var result=response.getReturnValue(); | |
var chartTypeOptions =[]; | |
var options =[]; | |
var selectedReport = component.get("v.selectedReport"); | |
var selectedChartType = component.get("v.selectedChartType"); | |
console.log('chartTypeOption: '+chartTypeOption); | |
for (let index = 0; index < chartTypeOption.length; index++) { | |
var isSelected = false; | |
if(selectedChartType!=null){ | |
if(selectedChartType == chartTypeOption[index]){ | |
isSelected = true; | |
} | |
} | |
else{ | |
component.set("v.selectedChartType",chartTypeOption[0]); | |
} | |
chartTypeOptions.push({ label: chartTypeOption[index], value: chartTypeOption[index], selected: isSelected}); | |
} | |
component.set("v.chartType",chartTypeOptions); | |
for (let index = 0; index < result.length; index++) { | |
var isSelected = false; | |
if(selectedChartType!=null){ | |
if(selectedReport == result[index]){ | |
isSelected = true; | |
} | |
} | |
else{ | |
component.set("v.selectedReport",result[0]); | |
} | |
options.push({ label: result[index], value: result[index], selected: isSelected}); | |
} | |
component.set("v.reports",options); | |
this.CreateChart(component,event,helper); | |
} | |
}); | |
$A.enqueueAction(action); | |
}, | |
updateSettings:function(component,event,helper){ | |
let action = component.get('c.updateSettings'); | |
action.setParams({ | |
"chartType": component.get("v.selectedChartType"), | |
"reportName" : component.get("v.selectedReport") | |
}); | |
action.setCallback(this,function(response){ | |
let state = response.getState(); | |
if(state == 'SUCCESS'){ | |
let result = response.getReturnValue(); | |
}else{ | |
console.log('Something went wrong!'); | |
} | |
}); | |
$A.enqueueAction(action); | |
} | |
}) |
ReportChartCmpCSS:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.THIS .select{ | |
width:100%; | |
height:35px; | |
} | |
.THIS .d1{ | |
margin-left:1%; | |
} | |
.THIS .slds-page-header { | |
border-radius:0px; | |
box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.10); | |
} |
ReportChartCntrl:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ReportChartCntrl { | |
@AuraEnabled | |
public static User fetchReportChartSettings(){ | |
User u = [select id,Report_Name__c,Chart_Type__c from User where id=:system.UserInfo.getUserId()]; | |
return u; | |
} | |
@AuraEnabled | |
public static void updateSettings(String chartType, String reportName){ | |
User u = [select id,Report_Name__c,Chart_Type__c from User where id=:system.UserInfo.getUserId()]; | |
if(chartType !='' && reportName !=''){ | |
u.Chart_Type__c = chartType; | |
u.Report_Name__c = reportName; | |
//update | |
update u; | |
} | |
} | |
@AuraEnabled | |
public static List<String> fetchReports() | |
{ | |
List<String> options = new List<String>(); | |
for(Report obj :[select id,name from report where Format='MATRIX' or Format ='Summary'] )//instead of BU_Project__c.Id pass actual id | |
{ | |
options.add(obj.Name); | |
} | |
system.debug('Option Returned: '+options); | |
return options; | |
} | |
@AuraEnabled | |
public static String getReportData(string reportName){ | |
//Using report id for example purpose | |
Report stdReport = [SELECT Id FROM Report WHERE Name =:reportName]; | |
// Get the Report data | |
Reports.ReportResults reportReturned =Reports.ReportManager.runReport(stdReport.Id, true); | |
system.debug('Report Data: '+JSON.serialize(reportReturned)); | |
//Return Report data in JSON serialize format. | |
return JSON.serialize(reportReturned); | |
} | |
} |
Happy coding 🙂
Thanks
Arun Kumar
Can you do it in LWC ? if yes, then please share the code too
LikeLike