Category: moodle-codescript

Moodle JS code to create chart using builtin chartjs

PHP Code to prepare the chart data

$context  = array();
 
            $context['chart']['labels'] = json_encode(['All', "Active", "Suspended"]);
            $context['chart']['dataset'] =json_encode(  array_values( 4,3,2 ));
// assuming file is under local/myplugin/templates/chart.mustache
echo  $OUTPUT->render_from_template('/local/myplugin/chart', $context) ;

JS Code under template file

/local/myplugin/templates/chart.mustache


<div>
        <canvas id="stats" class="aw_chart">

        </canvas>
</div>



{{#js}}
require([
'jquery',
'core/chartjs'
], function($, Chart) {

var chart_div = $("#stats");  // @TODO

var chartdata = {
    labels:{{{chart.labels}}}, // @TODO
    datasets: [{
    data: {{{chart.dataset}}}, //@TODO
    backgroundColor: ["#fe6384", "#36a2eb", "#fdce56"],
    borderWidth: 2
    }]
}

var config = {
    type: 'doughnut', // pie , bar, 
    data: chartdata,
    options: {
        responsive: true,
        maintainAspectRatio: false,
        aspectRatio: 1,
        legend: {

        position: 'left',
        labels:{
          // showing value with legends along with label
            generateLabels: function(chart) {
                var data = chart.data;
                if (data.labels.length && data.datasets.length) {
                    return data.labels.map(function(label, i) {
                        var meta = chart.getDatasetMeta(0);
                        var ds = data.datasets[0];
                        var arc = meta.data[i];
                        var custom = arc && arc.custom || {};
                        var valueAtIndexOrDefault = Chart.helpers.valueAtIndexOrDefault;
                        var arcOpts = chart.options.elements.arc;
                        var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
                        var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
                        var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
                        var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
                        return {
                            text: label + " : " + value,
                            fillStyle: fill,
                            strokeStyle: stroke,
                            lineWidth: bw,
                            hidden: isNaN(ds.data[i]) || meta.data[i].hidden,

                            index: i
                        };
                    });
            }else{
                return [];
                }
            },
            usePointStyle: true,
        }
     },
    }
};

chart = new Chart(chart_div, config);

});

{{/js}}

Moodle php code to create chart using builtin chartjs

Data Prepration


$sales = new \core\chart_series('Sales', [1000, 1170, 660, 1030]);
$expenses = new \core\chart_series('Expenses', [400, 460, 1120, 540]);
$labels = ['2004', '2005', '2006', '2007'];

Pie Chart / Donought

$chart = new \core\chart_pie();
//$chart->set_doughnut(true); // for donought chart
$chart->set_title('PIE CHART');
$chart->add_series($sales);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Line Chart

$chart = new \core\chart_line();
//$chart->set_smooth(true);
$chart->set_title('SMOOTH LINES CHART');
$chart->add_series($sales);
$chart->add_series($expenses);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Bar Chart

$chart = new \core\chart_bar();
$chart->set_title('BAR CHART');
// for stacked
// $chart->set_title('STACKED BAR CHART');
// $chart->set_stacked(true);
// for horizontal
// $chart->set_title('HORIZONTAL BAR CHART');
// $chart->set_horizontal(true);

$chart->add_series($sales);
$chart->add_series($expenses);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Bar Chart with line chart

$chart = new \core\chart_bar();
$chart->set_title('BAR CHART COMBINED WITH LINE CHART');
$expensesline = new \core\chart_series('Expenses', [400, 460, 1120, 540]);
$expensesline->set_type(\core\chart_series::TYPE_LINE);
$chart->add_series($expensesline);
$chart->add_series($sales);
$chart->set_labels($labels);
echo $OUTPUT->render($chart);

Series Chart

$hills = new \core\chart_series('Hills', [700, 870, 660, 950]);
$mountain = new \core\chart_series('Mountain', [400, 460, 1350, 540]);
$sky = new \core\chart_series('Sky', [1400, 1500, 1550, 1500]);
$chart = new \core\chart_line();
$chart->set_title('AREA FILL CHART');
$chart->add_series($hills);
$chart->add_series($mountain);
$chart->add_series($sky);
$chart->set_labels($labels);
$hills->set_smooth(true);
$hills->set_fill('origin');
$mountain->set_fill('-1');
$sky->set_fill('end');
echo $OUTPUT->render($chart);

Legend Options

// hide legend
$chart->set_legend_options(['display' => false]);

// legend position
$chart->set_legend_options(['position' => 'left', 'reverse' => true]);