Claude Skill

ux-chartjs

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.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Download smnandre-symfony-ux-skills-skills_ux-chartjs-78c25ed.zip · 3 KB

Install

skills CLI npx skills add https://github.com/smnandre/symfony-ux-skills/tree/main/skills/ux-chartjs
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install smnandre-symfony-ux-skills@llmmart
Git git clone https://github.com/smnandre/symfony-ux-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole smnandre/symfony-ux-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

UX Chart.js

Build a chart in PHP, render it with render_chart(), and let a Stimulus controller draw it with Chart.js (version 3 or 4). Data and options are plain PHP arrays passed as-is to Chart.js.

Installation

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

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]);
    }
}
<div style="position: relative; height: 320px">
    {{ render_chart(chart) }}
</div>

Keys follow the Chart.js documentation 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:

{{ render_chart(chart, {'data-controller': 'sales-chart'}) }}
// 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:

php bin/console importmap:require chartjs-plugin-zoom   # or: npm install chartjs-plugin-zoom
// 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:

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)]],
        ]);
    }
}
<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

See Also

  • live-component: re-render the chart from server state
  • stimulus: custom controllers listening to the chartjs:* events
Files (symfony-ux-skills)
  • SKILL.md 7.7 KB
    ---
    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
    

Comments

Sign in to join the conversation.

No comments yet. Start the conversation.

Reviews (0)

No reviews yet.