How to Implement Google Charts in Visualforce page for specific record ?

Thursday, August 13, 2015

Google Charts implement using visualforce page for Opportunity record as per the Stage


Here is the solution for Google charts implement into your visualforce page and you will get superb Output,

See below screenshot that i have made by using visualforce page and apex Class



In above screenshot left chart show the opportunity stage and how many record it has,
and right chart show the total number of amount for each opportunity stage.

Let's have a look into the code :

Apex class :

Public Class GoogleChartOpportunity{

    public String opportunitiesByStage{get;set;}
    public String opportunityByStageColors{get;set;}
   
    public String opportunityAmountByStage{get;set;}
    public String opportunityAmountByStageColors{get;set;}
   
    public GoogleChartOpportunity(){
   
    // Default Colors for Each stage.
        Map<String,String> mapStageNameToColor = new Map<String,String>();
            mapStageNameToColor.put('Prospecting','#25A6DF');
            mapStageNameToColor.put('Qualification','#676566');
            mapStageNameToColor.put('Needs Analysis','#585858');
            mapStageNameToColor.put('Value Proposition','#25A7E1');
            mapStageNameToColor.put('Id. Decision Makers','#373739');
            mapStageNameToColor.put('Perception Analysis','#676566');
            mapStageNameToColor.put('Proposal/Price Quote','#373739');
            mapStageNameToColor.put('Negotiation/Review','#373739');
            mapStageNameToColor.put('Closed Won','#676566');
       
   
     opportunitiesByStage = '';
     opportunityByStageColors = '';
       
        for(AggregateResult ar : [Select count(Id), StageName from Opportunity Group By StageName]){
            String oppStageName = String.ValueOf(ar.get('StageName'));
            opportunityByStageColors = (opportunityByStageColors == '' ? mapStageNameToColor.get(oppStageName) : opportunityByStageColors+','+mapStageNameToColor.get(oppStageName));
            opportunitiesByStage = (opportunitiesByStage == '' ? oppStageName+'#'+Integer.valueOf(ar.get('expr0')) : opportunitiesByStage+'~'+oppStageName+'#'+Integer.valueOf(ar.get('expr0')));
        }
       
     opportunityAmountByStage = '';
     opportunityAmountByStageColors = '';
       
        for(AggregateResult ar : [Select SUM(Amount), StageName from Opportunity Group By StageName]){
            String oppStageName = String.ValueOf(ar.get('StageName'));
            opportunityAmountByStageColors = (opportunityAmountByStageColors == '' ? mapStageNameToColor.get(oppStageName) : opportunityAmountByStageColors+','+mapStageNameToColor.get(oppStageName));
            opportunityAmountByStage = (opportunityAmountByStage == '' ? String.ValueOf(ar.get('StageName'))+'#'+Double.valueOf(ar.get('expr0')) : opportunityAmountByStage+'~'+String.ValueOf(ar.get('StageName'))+'#'+Double.valueOf(ar.get('expr0')));
        }
    }      
}

Visualforce Page :

<apex:page controller="GoogleChartOpportunity" sidebar="false" showHeader="false">
   
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
   
    <script type='text/javascript'>
        google.load('visualization', '1', {packages:['corechart']});
    </script>
     
    <script>
        function drawOpportunityVisualization(){
            //Preparing the array for which colors we need to display on chart.
            var oppByStageolorSet = new Array();
            var tmp = '{!opportunityByStageColors}';
            for ( var i = 0; i < tmp.split(',').length; i++ ) {
                oppByStageolorSet.push(tmp.split(',')[i]);
               
            }
               
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Stage Name');
            data.addColumn('number', 'Record Count');
           
            var oppStages = '{!opportunitiesByStage}'
            for(var i=0; i<oppStages.split('~').length;i++){
                var stageName = oppStages.split('~')[i].split('#')[0];
                var recCount = oppStages.split('~')[i].split('#')[1];
                data.addRow([stageName,parseInt(recCount)]);
            }
           
            var visualization = new google.visualization.ColumnChart(document.getElementById('chart_div'));
               
            var options = {
                title: 'OPPORTUNITIES BY STAGE',
                backgroundColor:'#F2F7FB',
                colors: oppByStageolorSet,
                legend:{position: 'none'},
                width: 500,
                height: 400
            };
            visualization.draw(data, options);
            google.visualization.events.addListener(visualization, 'select', function(){
                var selectedStageName = data.getValue(visualization.getSelection()[0].row, 0);
            });
        }
       
        function drawOpportunityAmountByStage(){
           
            //Preparing the array for which colors we need to display on chart.
           
            var oppAmountByStageolorSet = new Array();
            var tmp1 = '{!opportunityAmountByStageColors}';
            for ( var i = 0; i < tmp1.split(',').length; i++ ) {
                oppAmountByStageolorSet.push(tmp1.split(',')[i]);
               
            }
           
            var data = new google.visualization.DataTable();
           
            data.addColumn('string','Stage Name');
            data.addColumn('number','Total Amount');
            var Amount = '{!opportunityAmountByStage}';
            for(var j=0; j<Amount.split('~').length; j++){
               
                var stageName = Amount.split('~')[j].split('#')[0];
                var AmountTotal = parseFloat(Amount.split('~')[j].split('#')[1]);
               
                data.addRow([stageName,AmountTotal]);
            }
           
            var formatter = new google.visualization.NumberFormat(
                 {negativeColor: 'red', negativeParens: true, pattern: '$###,###'});
                formatter.format(data, 1);
           
            var visualization = new google.visualization.PieChart(document.getElementById('AmountChartDiv'));
           
            var options = {
                title: 'ESTIMATED AMOUNT',
                backgroundColor:'#F2F7FB',
                pieSliceText: 'value',
                pieHole: 0.4,
                width: 500,
                height: 400,
                colors: oppAmountByStageolorSet
            };
            visualization.draw(data, options);
            google.visualization.events.addListener(visualization, 'select', function(){
                var selectedStageName = data.getValue(visualization.getSelection()[0].row, 0);
            });
        }
       
        function showOpportunityCharts(){
            drawOpportunityVisualization();
            drawOpportunityAmountByStage();
        }
    </script>
    <style>
          a.active {
            background-color: #25A6DF;
          }
    </style>
    <apex:form >
        <apex:outputPanel >
            <script>
                google.setOnLoadCallback(showOpportunityCharts);
            </script>
            <table width="100%" cellpadding="0" cellspacing="0">
                <tr>
                    <td width="50%" style="padding-left:15%; padding-top:15%"><div id='chart_div' style="height: 300px; width: 400px;"/></td>
                    <td width="50%" style="padding-top:15%"><div id='AmountChartDiv' style="height: 300px; width: 400px;"/></td>
                </tr>
            </table>
        </apex:outputPanel>  
    </apex:form>

</apex:page>

No comments: