how to set a custom tick format in chartjs options from laravel controller?

495 views Asked by At

I'm trying to customize the ticks labels by adding the $ sign before the actual value in a bar chart via Laravel Charts.
In chartjs docu (https://www.chartjs.org/docs/2.7.3/axes/labelling.html#creating-custom-tick-formats) it's described to do it like this:

var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
    scales: {
        yAxes: [{
            ticks: {
                // Include a dollar sign in the ticks
                callback: function(value, index, values) {
                    return '$' + value;
                }
            }
        }]
    }
}

I'm struggling with the callback function because I don't know how to do this in the chart controller - currently it looks like this (I just put it as a js formatted string), but it doesn't work:

$this->chart->options([
        'maintainAspectRatio' => false,
        'showLines' => false,
        'scales'              => [
            'xAxes' => [],
            'yAxes' => [
                [
                    'ticks' => [
                        'display' => true,
                        'callback' => "{function(value, index, values) {
                            return '$' + value;
                        }}",
                    ],
                ],
            ],
        ],
    ]);
1

There are 1 answers

0
chrisM On BEST ANSWER

It was my first time working with charts in backpack, but after some trials I was able to fix it by using rawObject:

$this->chart->options([
        'maintainAspectRatio' => false,
        'showLines' => true,
        'scales' => [
            'xAxes' => [],
            'yAxes' => [
                [
                    'ticks' => [
                        'display' => true,
                        'callback' => $this->chart->rawObject('euroLabel')
                    ],
                ],
            ],
        ],
        'legend' => [
            'display' => false
        ],
        'tooltips' => [
            'callbacks' => [
                'label' => $this->chart->rawObject('euroLabelTooltip')
            ]
        ]
    ]);

and in js:

function euroLabel(value, index, values) {
    return currencyLabels.format(value);
}

while currencyLable looks like this:

var currencyLabels = new Intl.NumberFormat('de-AT', {
    style: 'currency',
    currency: 'EUR',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
});