[Chartjs]-ChartJS with Symfony 4.4 (UX component)

2👍

Here’s the answer. Pretty close to @fbunhlak!

import {Controller} from 'stimulus';

export default class extends Controller {

connect() {
    this.element.addEventListener('chartjs:connect', this._onConnect);
}

_onConnect(event) {
    event.detail.chart.options.tooltips.callbacks.label = function (tooltipItem, data) {
        let label = data.labels[tooltipItem.index] || '';

        if (label) {
            label += ': ';
        }

        const sum = data.datasets[0].data.reduce((accumulator, currentValue) => accumulator + currentValue);
        const value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];

        label += Number((value / sum) * 100).toFixed(2) + '%';

        return label;
    };
}

}

0👍

Try to follow this example

// mychart_controller.js

import { Controller } from 'stimulus';

export default class extends Controller {
    connect() {
        this.element.addEventListener('chartjs:connect', this._onConnect);
    }

    disconnect() {
        // You should always remove listeners when the controller is disconnected to avoid side effects
        this.element.removeEventListener('chartjs:connect', this._onConnect);
    }

    _onConnect(event) {
        event.detail.chart.options.plugins = {
            datalabels: {
                formatter: (value, ctx) => {
                    return value.toFixed(2) + "%";
                }
            }
        }
    }
}

Leave a comment