ux
ux copied to clipboard
[ChartJS] Use plugin ?
Hello ! Is it possible to use ChartJS plugins with ux-chartjs? Like chartjs-plugin-datalabels for example.
Hmm, this is not quite possible! I initially was thinking "yes", and here was my solution:
Use the event system to "modify" chart options - https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration
We document it a bit here: https://github.com/symfony/ux/tree/main/src/Chartjs#extend-the-default-behavior
You would listen to the
chartjs:pre-connect
event, then do something likeevent.detail.plugins = [ChartDataLabels]
.
BUT, this won't work, as only the options
for chartjs are exposed on the event. We need to fix this line to include plugins
also... or everything: https://github.com/symfony/ux/blob/9d72de167e9d1fdb90f06361a4cbb6b0a412a9eb/src/Chartjs/Resources/assets/src/controller.js#L22
Another solution is to register the plugin globally - the first code block shown here - https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration. You could do that in assets/app.js
for example :)
I will leave this open, because the above problem should be fixed imo.
Thanks for your reply ! It's a good alternative to register the plugin globally, but how to make the Chart.register(ChartDataLabels);
without Chart
and chartjs
package installed ?
If you installed ux-chartjs, the Chartjs package should be installed as well. If it's not there is an issue :) .
Globally registering plugins is probably the best way to go indeed, especially since UX 2.0 which uses ChartJS 3. In ChartJS 3, you can register a series of plugins globally and choose which one to use using options:
https://www.chartjs.org/docs/latest/developers/plugins.html#disable-plugins
@weaverryan perhaps we could recommend this in the README?
I've got this to work following the suggestion from @weaverryan Then disabling the plugin for all Charts except for the ones where the plugin is needed by setting the following:
$chart->setOptions([
'plugins' => [
'datalabels' => false,
],
]);
It would be nice though if it was possible to listen to chartjs:pre-connect
and set the plugin as event.detail.plugins = [ChartDataLabels]
.
I have set this in my app.js
import { autocolors } from 'chartjs-plugin-autocolors';
Chart.register(autocolors);
but I still get a grey pie chart. What am I missing?
Got it working, but had to load Chart also in app.js? The below in my app.js seem to work
import Chart from 'chart.js/auto';
import autocolors from 'chartjs-plugin-autocolors';
Chart.register(autocolors);
This is fixed by #870. Well, using plugins is already documented. But that PR allows for the event.detail.plugins = [ChartDataLabels].
suggested by @apphancer