Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ux Chartjs Laravel Package

symfony/ux-chartjs

Symfony UX Chart.js is a Symfony bundle that integrates Chart.js into Symfony apps. Part of the Symfony UX initiative, it helps you build and render interactive charts with modern UX tooling. Documentation and issues are managed in the main symfony/ux repo.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package (requires Symfony 7.4+, PHP 8.4+):
    composer require symfony/ux-chartjs
    
  2. Enable the bundle in config/bundles.php:
    return [
        // ...
        Symfony\UX\ChartJsBundle\ChartJsBundle::class => ['all' => true],
    ];
    
  3. Install Chart.js via Flex:
    composer require chartjs/chart.js
    
  4. Basic Twig usage (UX 3.x component syntax):
    {% use 'chartjs_chart.html.twig' %}
    {{ component('chartjs_chart', {
        type: 'line',
        data: {
            labels: ['Jan', 'Feb', 'Mar'],
            datasets: [{
                label: 'Sales',
                data: [10, 20, 30]
            }]
        }
    }) }}
    

First Use Case: Static Dashboard Chart

  • Controller: Pass data via Twig variables or LiveComponent props.
    // src/Controller/ChartController.php
    public function dashboard(ChartController $controller): Response
    {
        return $this->render('dashboard.html.twig', [
            'chartData' => $controller->getSalesData(),
        ]);
    }
    
  • Twig: Embed data directly or use LiveComponent for reactivity.
    {{ component('chartjs_chart', {
        type: 'bar',
        data: chartData,
        options: { responsive: true }
    }) }}
    

Implementation Patterns

Core Workflows

  1. Data Binding:

    • Static Data: Pass PHP arrays directly to Twig.
    • Dynamic Data: Use LiveComponents to update charts via WebSocket/Mercure.
      {{ component('live_chart', {
          data: controller.fetchLiveData()
      }) }}
      
    • API Data: Fetch from API Platform or custom endpoints.
      {{ component('chartjs_chart', {
          data: controller.apiFetch('metrics')
      }) }}
      
  2. Chart Customization:

    • Options: Configure via options key (Chart.js config).
      options: {
          plugins: { title: { display: true, text: 'Monthly Sales' } },
          scales: { y: { beginAtZero: true } }
      }
      
    • Plugins: Register Chart.js plugins in assets/app.js:
      import { Chart } from 'chart.js';
      import annotationPlugin from 'chartjs-plugin-annotation';
      Chart.register(annotationPlugin);
      
  3. Live Updates:

    • Stimulus Controller: Extend for custom logic.
      // assets/controllers/chart_controller.js
      import { Controller } from '@hotwired/stimulus';
      export default class extends Controller {
          connect() {
              this.chart = this.element.chart;
          }
          updateData(data) {
              this.chart.data = data;
              this.chart.update();
          }
      }
      
    • Twig: Bind to Stimulus actions.
      {{ component('chartjs_chart', {
          data: chartData,
          stimulus: 'chart'
      }) }}
      
  4. Reusable Components:

    • Twig Includes: Create modular chart templates.
      {# templates/components/chart/line.html.twig #}
      {% extends 'chartjs_chart.html.twig' %}
      {% block type %}line{% endblock %}
      
    • LiveComponent: Encapsulate logic.
      // src/Components/ChartComponent.php
      public function getSalesData(): array
      {
          return $this->getSalesRepository()->findMonthlySales();
      }
      

Integration Tips

  • Asset Management:
    • Webpack Encore: Ensure chart.js is in package.json and resolved in webpack.config.js.
    • Vite: Add to vite.config.js:
      optimizeDeps: {
          include: ['chart.js', 'chartjs-plugin-datalabels']
      }
      
  • Symfony UX 3.x:
    • Use use statements for components (not component() helper).
    • Leverage LiveComponent for real-time updates:
      {{ component('live_chart', {
          data: controller.streamData()
      }) }}
      
  • Debugging:
    • Check browser console for Stimulus/Chart.js errors.
    • Use {{ dump(component('chartjs_chart')) }} to inspect component state.

Gotchas and Tips

Common Pitfalls

  1. Symfony 7.x Migration:

    • Twig Component Syntax: UX 3.x requires use statements, not component() helper.
      {# ❌ Old #}
      {{ component('chartjs_chart', {}) }}
      
      {# ✅ New #}
      {% use 'chartjs_chart.html.twig' %}
      
    • Webpack/Vite: Symfony 7.x defaults to Vite; ensure chart.js is optimized.
      // vite.config.js
      optimizeDeps: {
          include: ['chart.js']
      }
      
  2. Chart.js Version Conflicts:

    • Auto-Registration: UX 3.x uses explicit Chart.register() (no chartjs/auto).
      // assets/app.js
      import { Chart } from 'chart.js';
      import { LineController } from 'chartjs-chart-line';
      Chart.register(LineController);
      
    • Plugin Compatibility: Update plugins to Chart.js v4+ (e.g., chartjs-plugin-datalabels@2.x).
  3. LiveComponent Quirks:

    • Data Binding: Ensure data-symfony--ux-chartjs--chart-view-value updates trigger re-renders.
    • Stimulus Events: Use chartjs:connect and chartjs:view-value-change for custom logic.
      this.element.addEventListener('chartjs:view-value-change', (e) => {
          console.log('Data updated:', e.detail);
      });
      
  4. Asset Loading:

    • Missing Charts: Verify chart.js is in package.json and built.
      npm install chart.js
      npm run build
      
    • Vite Errors: Check vite.config.js for missing dependencies.

Debugging Tips

  • Stimulus Debugging:
    • Enable Stimulus debug mode in assets/app.js:
      import { Application } from '@hotwired/stimulus';
      const application = Application.start();
      application.debug = true; // Logs all Stimulus actions
      
  • Chart.js Console:
    • Check for Chart is not defined errors (missing chart.js import).
    • Use console.log(this.chart) in Stimulus controllers to inspect instances.
  • Twig Component Dumps:
    • Inspect component state with:
      {{ dump(component('chartjs_chart')) }}
      

Extension Points

  1. Custom Chart Types:

    • Extend ChartJsController for reusable logic:
      // src/Controller/CustomChartController.php
      public function getBarChartData(): array
      {
          return ['labels' => [...], 'datasets' => [...]];
      }
      
    • Use in Twig:
      {{ component('custom_chart', {}) }}
      
  2. Stimulus Extensions:

    • Add custom methods to chart_controller.js:
      updateData(data) {
          this.chart.data = data;
          this.chart.update();
          this.dispatch('chart-updated', { detail: data });
      }
      
    • Trigger from Twig:
      <button data-action="click->chart#updateData">Refresh</button>
      
  3. Mercure Integration:

    • Update charts via Mercure updates:
      {{ component('live_chart', {
          mercureUpdate: controller.getMercureUpdate()
      }) }}
      
    • Stimulus controller:
      connect() {
          this.subscription = Mercure.subscribe(this.data.get('mercureUpdate'), (event) => {
              this.updateData(JSON.parse(event.data));
          });
      }
      

Configuration Quirks

  • Asset Paths:
    • UX 3.x moves assets to assets/src (not Resources/assets/).
    • Update package.json scripts if needed:
      "scripts": {
          "build": "vite build assets/src --base /"
      }
      
  • PHP 8.4+:
    • Use named arguments for ChartJsController methods:
      $this->render('chart.html.twig', [
          'chartData' => $this->getChartData(type: 'line'),
      ]);
      
  • Symfony 7.4+:
    • Enable framework.asset_mapper in config/packages/framework.yaml:
      framework:
          asset_mapper: true
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
symfony/ai-symfony-mate-extension
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata