Friday, June 1, 2012

Google Charts in Visualforce Page


Google Charts in Visualforce Page:
   
     We have requirement populate the Charts in Salesforce by counting account type.  Google provides the online editor for creating charts and just pass our values/dimensions.
  We have written apex controller class which gets count of Account type and passing these values to Google API’s chart URL. Google gives us chart image then we populate in to Visualforce.
    We can create charts from Google site editor http://code.google.com/apis/chart/image/docs/chart_wizard.html

   As given below VF page code and apex class have example of chart.

VF page code:
<apex:page controller="googleChartController" tabStyle="Account">
<apex:sectionHeader title=" Type of Account"></apex:sectionHeader>
<apex:image url="{!chartData}"></apex:image>
</apex:page>


Controller class code:
public class googleChartController {
private String chartData;

public String getChartData()
{
 return chartData;
}
//Contructor
public googleChartController ()
{
 //get obtain a list of picklist values
 Schema.DescribeFieldResult F = Account.Type.getDescribe();
 List<Schema.PicklistEntry> P = F.getPicklistValues();
 //where chart data should be stored.
 List<ChartDataItem> items = new List<ChartDataItem>();

 //iterate through each picklist value and get number of accounts
 // I wish we could do GROUP BY in SOQL!
 for(Schema.PicklistEntry pValue : P)
 {
    integer Count = [select count() from Account where Type = :pValue.getValue() limit 10000];
    if (Count > 0)
      items.add(new ChartDataItem(pValue.getValue()+ '-['+ Count.format() + ']' , Count.format()));
 }
 //Prepare the chart URL
 String chartPath = 'http://chart.apis.google.com/chart?chs=600x200&cht=p3';
 chartData = chartPath +  getChartData(items);
}

private String getChartData(List<ChartDataItem> items)
{
 String chd = ''; //23,34,56
 String chl = ''; //Hello|World

 for(ChartDataItem citem : items)
 {
    chd += citem.ItemValue + ',';
    chl += citem.Label + '|';
 }
 //remove the last comma or pipe
 chd = chd.substring(0, chd.length() -1);
 chl = chl.substring(0, chl.length() -1);

 String result = '&chd=t:' + chd + '&chl=' + chl;
 return result;
}// end of method

public class ChartDataItem
{
 public String ItemValue {  get;  set; }
 public String Label {   get;   set; }
 public ChartDataItem(String Label, String Value)
 {
    this.Label = Label;
    this.ItemValue = Value;
  }
 }
}// end of class

No comments:

Post a Comment