Monday, June 3, 2013

Using apex:repeat to populate Google Charts data

Here is an easy way to integrate Google Charts into your Visualforce page with a simple controller!

Here is the controller example:

public class exampleController{
    public List<tableWrapper> getTableVal() {        
        List<tableWrapper> data = new List<tableWrapper>();                
        data.add(new tableWrapper('Work', 11));
        data.add(new tableWrapper('Eat', 2));
        data.add(new tableWrapper('Commute', 2));
        data.add(new tableWrapper('Watch TV', 2));
        data.add(new tableWrapper('Sleep', 7));    
        return data;
    }    
    public class tableWrapper {
        public string title {get; set;}
        public double val {get; set;}
        public tableWrapper(string c, double v) {
            title = c;
            val = v;
        }
    }    
}

In this controller example, I am not using any salesforce objects for the data. I just created the object and the data in the controller but you can easily do the same with salesforce objects by querying the data.

Here is an example of the Visualforce page:

<apex:page controller="exampleController">
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day']
            <apex:repeat value="{!TableVal}" var="x">
                ,['{!x.title}',  {!x.val}]
            </apex:repeat>
        ]);
        var options = {
          title: 'My Daily Activities'
        };
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
</apex:page>
I used apex repeat to dynamically add the data in the javascript section to create the Google Chart. Simple and easy!

Here is the resulting chart:


2 comments: