Source: http://nvd3.org/

Visualizing Salesforce Reports with D3 Charts

Less than 30 lines of code!

Arun V
Salesforce Analytics
2 min readOct 15, 2013

--

SourceCode: https://github.com/arun-sfdc/Analytics-API/blob/master/d3ReportChart.page

The Analytics API really opens up what we can do with Salesforce Reports. D3.js is one of the most powerful and important charting engines and in this blog post we will explore how to integrate it with report data.

Step1: Execute the Report

Thanks to the Summer’13 Force.com enhancement that allows use to access REST APIs directly from Visualforce, we can run a report and get the dataset in less than 10 lines of code.

$.ajax(‘/services/data/v29.0/analytics/reports/{!$CurrentPage.parameters.reportId}’,{ beforeSend: function(xhr) { xhr.setRequestHeader(‘Authorization’, ‘Bearer {!$Api.Session_ID}’); },success: function(response) { console.log(response); } });

Step2: Setup a Sample Chart

Starting with a sample chart makes it easier to understand the data format. Instead of using D3.js directly, we will be using the derivate NVD3 which is easier to configure and has a simpler data format. The following sample is from StackExchange.

var chart = nv.models.multiBarChart(); d3.select('#chart').datum([ { key: "S1", values:[ { x : "A", y : 40 },{ x : "B", y : 30 },{ x : 5, y : 20 } ] }, { key: "S2", values:[ { x : "A", y : 60 },{ x : "B", y : 50 },{ x : 5, y : 70 } ] } ]).transition().duration(500).call(chart);

Step3: Wiring it together

The final step is to map the report results from the API into the chart data format. The salesforce “Matrix” report format is best suited to be mapped into a multi-bar chart. Its evident from the mapping code that the Analytics API data format has been designed to be easily pluggable into chart engines.

var chartData = []; $.each(response.groupingsDown.groupings, function(di, de) { var values = []; chartData.push({"key":de.label, "values": values}); $.each(response.groupingsAcross.groupings, function(ai, ae) { values.push({"x": ae.label, "y": response.factMap[de.key+"!"+ae.key].aggregates[0].value}); }); });

The complete self-contained source code for the VisualForce page is available here on GitHub.

SourceCode: https://github.com/arun-sfdc/Analytics-API/blob/master/d3ReportChart.page

There you have it, Salesforce reports as D3 charts !!

--

--