Skip to content
Back to skills

Ux Chartjs

ASecurity

Symfony UX Chart.js: bar, line and pie charts from PHP data in Symfony and Twig. Use for axes, tooltips, ChartBuilderInterface, Chart::TYPE_*, setData(), setOptions(), render_chart(), Chart.js plugins, chartjs:pre-connect, chartjs:connect and charts in LiveComponents.

  • 191 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 2, 2026
ai-agentsjavascriptgojavaphpbashdocumentation

Works with

  • cli

Security analysis

A92/100
  • mediumInstalls packages at runtime which could introduce malicious dependencies

Pro shows the line behind each finding and how to fix it

Scanned December 2, 2026

npx -y skills add smnandre/symfony-ux-skills --skill ux-chartjs --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Ux Chartjs?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Ux Chartjs
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/smnandre-ux-chartjs/badge)](https://www.skillsdirectory.com/skills/smnandre-ux-chartjs)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: ux-chartjs
description: 'Symfony UX Chart.js: bar, line and pie charts from PHP data in Symfony and Twig. Use for axes, tooltips, ChartBuilderInterface, Chart::TYPE_*, setData(), setOptions(), render_chart(), Chart.js plugins, chartjs:pre-connect, chartjs:connect and charts in LiveComponents.'
license: MIT
metadata:
  author: Simon André
  url: https://smnandre.dev
---

# UX Chart.js

Build a chart in PHP, render it with `render_chart()`, and let a Stimulus controller draw it with [Chart.js](https://www.chartjs.org) (version 3 or 4). Data and options are plain PHP arrays passed as-is to Chart.js.

## Installation

```bash
composer require symfony/ux-chartjs
```

With AssetMapper, the Flex recipe adds `chart.js` to `importmap.php`. With Webpack Encore or Reprise, run `npm install --force` and rebuild.

## Quick Reference

```
ChartBuilderInterface::createChart(Chart::TYPE_LINE)   New chart
$chart->setData([...])                                 Chart.js "data" (labels, datasets)
$chart->setOptions([...])                              Chart.js "options"
{{ render_chart(chart) }}                              <canvas> with the Stimulus controller
{{ render_chart(chart, {class: 'h-64'}) }}             Extra HTML attributes on the <canvas>
```

Types: `TYPE_LINE`, `TYPE_BAR`, `TYPE_RADAR`, `TYPE_PIE`, `TYPE_DOUGHNUT`, `TYPE_POLAR_AREA`, `TYPE_BUBBLE`, `TYPE_SCATTER`.

## Building a Chart

```php
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
use Symfony\UX\Chartjs\Model\Chart;

final class DashboardController extends AbstractController
{
    #[Route('/dashboard', name: 'app_dashboard')]
    public function __invoke(ChartBuilderInterface $chartBuilder): Response
    {
        $chart = $chartBuilder->createChart(Chart::TYPE_LINE)
            ->setData([
                'labels' => ['January', 'February', 'March', 'April'],
                'datasets' => [[
                    'label' => 'Sales',
                    'backgroundColor' => 'rgb(255, 99, 132)',
                    'borderColor' => 'rgb(255, 99, 132)',
                    'data' => [12, 19, 3, 25],
                ]],
            ])
            ->setOptions([
                'maintainAspectRatio' => false,
                'scales' => ['y' => ['suggestedMin' => 0]],
            ]);

        return $this->render('dashboard/index.html.twig', ['chart' => $chart]);
    }
}
```

```twig
<div style="position: relative; height: 320px">
    {{ render_chart(chart) }}
</div>
```

Keys follow the [Chart.js documentation](https://www.chartjs.org/docs/latest/) exactly (`backgroundColor`, `suggestedMin`...). Chart.js sizes the canvas from its parent: give the parent a height when `maintainAspectRatio` is `false`.

## JavaScript Callbacks

Data and options travel as JSON, so PHP can only send values. For a tick formatter, a tooltip callback or `onClick`, attach your own Stimulus controller and edit the config before the chart is created:

```twig
{{ render_chart(chart, {'data-controller': 'sales-chart'}) }}
```

```javascript
// assets/controllers/sales_chart_controller.js
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
    initialize() {
        this.onPreConnect = this.onPreConnect.bind(this);
        this.onConnect = this.onConnect.bind(this);
    }

    connect() {
        this.element.addEventListener('chartjs:pre-connect', this.onPreConnect);
        this.element.addEventListener('chartjs:connect', this.onConnect);
    }

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

    onPreConnect(event) {
        // Merge into the existing options instead of replacing them
        const scales = (event.detail.config.options.scales ??= {});
        const y = (scales.y ??= {});
        y.ticks = { ...y.ticks, callback: (value) => `${value} EUR` };
    }

    onConnect(event) {
        event.detail.chart.options.onClick = (mouseEvent, elements) => { /* ... */ };
    }
}
```

## Events

Dispatched on the `<canvas>` with the `chartjs:` prefix; they bubble.

| Event | `event.detail` | When |
|-------|----------------|------|
| `chartjs:init` | `Chart` (the class) | Once, before the first chart on the page |
| `chartjs:pre-connect` | `config`, `options` | Before `new Chart()`: edit the config here |
| `chartjs:connect` | `chart` | Right after creation |
| `chartjs:view-value-change` | `data`, `options` | Before an update from new server data |
| `chartjs:disconnect` | `chart` | Before the chart is destroyed |

## Plugins

Install the plugin, then register it globally on `chartjs:init`, in a file loaded before any chart connects:

```bash
php bin/console importmap:require chartjs-plugin-zoom   # or: npm install chartjs-plugin-zoom
```

```javascript
// assets/app.js
import zoomPlugin from 'chartjs-plugin-zoom';

document.addEventListener('chartjs:init', (event) => {
    event.detail.Chart.register(zoomPlugin);
});
```

Configure it from PHP like any option: `'plugins' => ['zoom' => ['zoom' => ['wheel' => ['enabled' => true], 'mode' => 'xy']]]`.

## Live Charts

When the chart data changes, the controller updates the existing chart instead of recreating it. That makes it work inside a LiveComponent:

```php
use Symfony\UX\Chartjs\Builder\ChartBuilderInterface;
use Symfony\UX\Chartjs\Model\Chart;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent]
final class SalesChart
{
    use DefaultActionTrait;

    #[LiveProp(writable: true)]
    public string $period = 'month';

    public function __construct(
        private readonly ChartBuilderInterface $chartBuilder,
        private readonly SalesRepository $sales,
    ) {}

    public function getChart(): Chart
    {
        $points = $this->sales->totalsFor($this->period);

        return $this->chartBuilder->createChart(Chart::TYPE_BAR)->setData([
            'labels' => array_keys($points),
            'datasets' => [['label' => 'Sales', 'data' => array_values($points)]],
        ]);
    }
}
```

```twig
<div{{ attributes }}>
    <select data-model="period">
        <option value="week">Week</option>
        <option value="month">Month</option>
    </select>
    {{ render_chart(this.chart) }}
</div>
```

## Gotchas

- Register plugins on `chartjs:init` from `app.js`, loaded before the first chart connects, to catch that one-time event.
- `setOptions()` and `setData()` replace the whole array; build each one completely.
- Every Chart.js chart type and scale is registered, so any `type` works out of the box.
- In `pre-connect`, merge into `config.options` rather than reassigning a whole branch (`scales`, `plugins`): reassigning drops what PHP sent.

## References

- [Symfony UX package page](https://ux.symfony.com/chartjs) ([Markdown summary](https://ux.symfony.com/chartjs.md)) · [`symfony/ux-chartjs` on Packagist](https://packagist.org/packages/symfony/ux-chartjs).
- Try the [interactive chart demo](https://ux.symfony.com/chartjs#demo).
- See the [auto-updating chart with LiveComponent](https://ux.symfony.com/demos/live-component/chartjs).
- For chart rendering, plugins and extending the controller, see the [Symfony UX Chart.js documentation](https://symfony.com/bundles/ux-chartjs).
- For options passed to Chart.js, including tooltips, interactions and responsiveness, see the [Chart.js configuration reference](https://www.chartjs.org/docs/latest/configuration/).

## See Also

- **live-component**: re-render the chart from server state
- **stimulus**: custom controllers listening to the `chartjs:*` events

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.