ux icon indicating copy to clipboard operation
ux copied to clipboard

[ChartJS] unable to configure tootlip label callback

Open coderpauloo opened this issue 1 year ago • 1 comments

Hello,

I tried to configure a ChartJS pie label callback following the docs for the v3.8.2 of ChartJS used in the Symfony UX ChartJS v2.17: https://www.chartjs.org/docs/3.8.2/configuration/tooltip.html

Here is the config I tried to run :

image

but it only produces this error :

image

I have the same issues with other label callbacks. Has anyone tried to customize this and managed to do it successfully ? Is there a bug somewhere or did I miss something ?

coderpauloo avatar Jul 05 '24 16:07 coderpauloo

I don't think you can write JS code in PHP.

You probably should use a custom stimulus controller and define the callback on initialization

--> https://symfony.com/bundles/ux-chartjs/current/index.html#extend-the-default-behavior

smnandre avatar Jul 05 '24 19:07 smnandre

ok thanks, I'll try this way but it still feels weird the php configuration does not cover this part of the features

coderpauloo avatar Jul 08 '24 07:07 coderpauloo

I tried your solution by creating this custom controller :

` //piechart_controller.js import { Controller } from '@hotwired/stimulus';

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

disconnect() {
    this.element.removeEventListener('chartjs:pre-connect', this._onPreConnect);
}

_onPreConnect(event) {
    const chart = event.detail.chart;
    console.log('here');
    chart.config.options.plugins.tooltip.callbacks.label = function(context) {
      return 'test';
    };

    chart.update();
}

} `

twig :

{{ render_chart(expensesDistributionChart, {'data-controller': 'piechart'}) }}

But I can't manage to make this work, I don't even see my console.log, would you have any example of detailed documentation about how to set this up please ?

coderpauloo avatar Jul 08 '24 08:07 coderpauloo

You must update the config and not the chart, as it's not yet created in the preConnect event

https://symfony.com/bundles/ux-chartjs/current/index.html#extend-the-default-behavior

   _onPreConnect(event) {
        // The chart is not yet created
        // You can access the config that will be passed to "new Chart()"
        console.log(event.detail.config);
        
        // ...

This should work better

smnandre avatar Jul 08 '24 18:07 smnandre

Thanks a lot for your help and explanations, I managed to make it work the way I needed to :)

Have a nice day !

coderpauloo avatar Jul 09 '24 10:07 coderpauloo

I'm glad if i can help :)

Happy coding!

smnandre avatar Jul 09 '24 18:07 smnandre