2amigos yii2 chartjs widget : Show legend on chart

Hey all!

I wanted to show the legend of a pie chart using the 2amigos yii2 chartjs widget

Does anyone know how I show the legend of the Chart.js widget?

I see the Chart.js documentation refers to .generateLegend() that requires the legendTemplate chart option to be set.

It looks like the Yii2 widget the 2amigos have written (great job guys!!) does not seem to have this .generateLegend() callable out of the box?

Or am I missing something?

Ok, it looks like the widget is not going facilitate the call of this function.

As suggested by someone in the IRC chat, I will implement some JavaScript in the view.

When I have done so will post my code here for future reference.

I’ve been looking for a solution but nothing came up.

Since I need to display graphs in quite a few views, instead of implementing and repeating Javascript in view files, i extended the widget, and replicated registerClientScript(), and added the following line before the last line in the function:


$js .= "var legend = chartJS_{$id}.generateLegend();$('#chartLegend_{$id}').append(legend);";



in the view file, add where you want to display legend:


<div id="chartLegend_(name of id)"></div>

Hope someone will find this useful.

Cool! Thanks for posting! Will try this out when I get a chance.

It’s worked Thanks.