Integrating Visualforce and Google Charts

Integrating Visualforce with Google Charts allows you to create dynamic and visually appealing charts within your Salesforce environment. Visualforce is Salesforce's markup language for building custom user interfaces, and Google Charts is a powerful visualization library provided by Google. Here's a basic guide on how to integrate Visualforce with Google Charts:


<!-- MyChartPage.page -->
<apex:page controller="ChartController">
    <apex:includeScript value="https://www.gstatic.com/charts/loader.js"/>
    <script>
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = google.visualization.arrayToDataTable({!chartData});

            var options = {
                title: 'My Chart'
            };

            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }
    </script>

    <div id="chart_div" style="width: 900px; height: 500px;"></div>

</apex:page>


// ChartController.cls
public with sharing class ChartController {
    public String chartData { get; private set; }

    public ChartController() {
        // Fetch data from Salesforce
        List<Account> accounts = [SELECT Name, AnnualRevenue FROM Account LIMIT 10];

        // Prepare data for Google Chart
        List<List<Object>> data = new List<List<Object>>();
        data.add(new List<Object>{'Name', 'Annual Revenue'});
        for (Account acc : accounts) {
            data.add(new List<Object>{acc.Name, acc.AnnualRevenue});
        }

        // Convert data to JSON format
        chartData = JSON.serialize(data);
    }
}

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach