Back to Top

Use google chart on custom page in Magento 2

Updated 26 April 2023

In this blog, we will explain how we can use google chart on any custom page in Magento 2. Google Charts provides a perfect way to visualize data on your website. From simple line charts to complex hierarchical tree maps, the chart gallery provides a large number of ready-to-use chart types. Here, we will show column chart on custom page on frontend. For other type of charts, you can also check the google chart docs.

A chart (sometimes known as a graph) is a graphical representation for data visualization, in which “the data is represented by symbols, such as bars in a bar chart, lines in a line chart, or slices in a pie chart”. A chart can represent tabular numeric data, functions or some kinds of quality structure. Charts are often used to ease understanding of large quantities of data and the relationships between parts of the data. Charts can usually be read more quickly than the raw data.

Steps Involved to show google chart on custom page

1. First, create customchart_index_index.xml layout file.
File Path: <magento-path>/app/code/Webkul/CustomChart/view/frontend/layout/customchart_index_index.xml

<?xml version="1.0"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomChart
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="https://www.gstatic.com/charts/loader.js" src_type="url"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block name="custom_chart_page" template="Webkul_CustomChart::custompage.phtml" />
        </referenceContainer>
    </body>
</page>


2. Now, create csp_whitelist.xml file.
File Path: <magento-path>/app/code/Webkul/CustomChart/etc/csp_whitelist.xml

As of version 2.3.5, Magento supports CSP headers and provides ways to configure them. You can add a domain to the whitelist for a policy (like script-srcstyle-srcfont-src and others) by adding a csp_whitelist.xml to your custom module’s etc folder.

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomChart
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp/etc/csp_whitelist.xsd">
    <policies>
        <policy id="script-src">
            <values>
                <value id="gstatic" type="host">*.gstatic.com</value>
            </values>
        </policy>
        <policy id="style-src">
            <values>
                <value id="gstatic" type="host">*.gstatic.com</value>
            </values>
        </policy>
        <policy id="connect-src">
            <values>
                <value id="gstatic" type="host">*.gstatic.com</value>
            </values>
        </policy>
        <policy id="img-src">
            <values>
                <value id="gstatic" type="host">*.gstatic.com</value>
            </values>
        </policy>
        <policy id="font-src">
            <values>
                <value id="gstatic" type="host">*.gstatic.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>


3. Then, create controller Index.php file.
File Path: <magento-path>/app/code/Webkul/CustomChart/Controller/Index/Index.php

Searching for an experienced
Magento 2 Company ?
Find out More
<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomChart
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\CustomChart\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

/**
 * Webkul Marketplace Landing page Index Controller.
 */
class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Execute action
     *
     * @return \Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $customPageLabel = 'Custom Chart';
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__($customPageLabel));
        return $resultPage;
    }
}


4. Then, create custompage.phtml template file.
File Path: <magento-path>/app/code/Webkul/CustomChart/view/frontend/templates/custompage.phtml

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomChart
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
?>
<?php
$chartInfo = [
    'chart' => [
        ['Period', 'Rewarded Points', 'Redeemed Points'],
        ['Jan', 45, 20],
        ['Feb', 100, 70],
        ['Mar', 150, 40],
        ['Apr', 250, 150],
        ['May', 180, 130],
        ['Jun', 90, 60],
        ['Jul', 30, 10],
        ['Aug', 120, 90],
        ['Sep', 50, 40],
        ['Oct', 210, 110],
        ['Nov', 150, 120],
        ['Dec', 70, 40]
    ]
];
?>
<div class="reports-container row">
    <div class="reports-main col-m-8 col-m-push-4">
        <div class="reports-diagram-container">
            <div id="chart_div" style="height: 500px;"></div>
        </div>
    </div>
</div>

<script type="text/x-magento-init">
    {
        "*": {
            "Webkul_CustomChart/js/custom-chart": {
                "chartInfo": <?= /** @noEscape */ json_encode($chartInfo) ?>
            }
        }
    }
</script>


5. Then, create custom-chart.js file.
File Path: <magento-path>/app/code/Webkul/CustomChart/view/frontend/web/js/custom-chart.js

/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomChart
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
 define([
    'jquery',
    'Magento_Ui/js/modal/alert',
    'mage/translate'
], function ($, alert, $t) {
    'use strict';

    $.widget('mage.customchart', {
        /**
         * Options common to all instances of this widget.
         * @type {Object}
         */
        options: {
            chartDivId: "chart_div"
        },

        _create: function () {
            this._super();
            var self = this;

            /**
             * js code to draw chart
             * Reference: https://developers.google.com/chart/interactive/docs/gallery/columnchart
             */
            google.charts.load('current', {packages: ['corechart', 'bar']});
            google.charts.setOnLoadCallback(drawColColors);
             
            function drawColColors() {
                var chartDiv = document.getElementById(self.options.chartDivId);
            
                var options = {
                    title: '',
                    legend: { position: 'top' },
                    colors: ['#F5974D', '#32A8B4']
                };

                function drawDefaultChart() {
                    console.log(self.options.chartInfo.chart);
                    var defaultData = new google.visualization.arrayToDataTable(
                        self.options.chartInfo.chart
                    );

                    var defaultChart = new google.visualization.ColumnChart(chartDiv);
                    defaultChart.draw(defaultData, options);
                }

                drawDefaultChart();
            };
        }
    });

    return $.mage.customchart;
});


Now, the chart will be shown on the magento 2 custom page as below:

custom chart image


Other blogs

You can also check our other wonderful blogs related to magento2 with the following links:
1. How to Create Custom Module in Magento 2: https://webkul.com/blog/create-hello-module-in-magento2/
2. How to create a custom cache type in Magento: https://webkul.com/blog/how-to-create-a-custom-cache-type-in-magento/
Thanks,

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home