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

Stimulus Bundle Laravel Package

symfony/stimulus-bundle

Symfony bundle that integrates Stimulus with Symfony and Symfony UX. Adds Twig stimulus_* helpers for controllers/actions/targets, supports AssetMapper, and provides a service to build Stimulus data attributes for use in templates and services.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:

    composer require symfony/stimulus-bundle
    

    Ensure your config/bundles.php includes:

    return [
        // ...
        Symfony\UX\StimulusBundle\StimulusBundle::class => ['all' => true],
    ];
    
  2. Enable Stimulus in Twig: Add the bundle to your config/packages/twig.php:

    twig:
        globals:
            stimulus: '@stimulus'
    
  3. First Use Case: Create a Stimulus controller (e.g., assets/controllers/example_controller.js):

    import { Controller } from '@hotwired/stimulus';
    
    export default class extends Controller {
        connect() {
            console.log('Example controller connected!');
        }
    }
    

    Use it in a Twig template:

    <div {{ stimulus_controller('example') }}>
        This element will trigger the Stimulus controller.
    </div>
    
  4. Verify Asset Pipeline: Ensure assets/controllers.json is generated (AssetMapper) or your Webpack Encore config includes Stimulus controllers.


Implementation Patterns

Core Workflows

1. Twig Integration

  • Controllers:

    {{ stimulus_controller('modal', { 'target': 'modal' }) }}
    

    Renders: data-controller="modal" data-modal-target="modal".

  • Actions:

    {{ stimulus_action('modal#open') }}
    

    Renders: data-action="modal#open->click".

  • Targets:

    {{ stimulus_target('modal', 'closeButton') }}
    

    Renders: data-modal-target="closeButton".

2. Dynamic Data Attributes

Use the StimulusHelper service in PHP to generate attributes dynamically:

$helper = $this->container->get('stimulus.helper');
$attributes = $helper->getControllerAttributes('modal', ['target' => 'modal']);
// Output: ['data-controller' => 'modal', 'data-modal-target' => 'modal']

3. Symfony UX Integration

  • Turbo: Combine with symfony/ux-turbo-bundle for SPA-like navigation.
    {{ stimulus_controller('turbo-frame', { 'target': 'frame' }) }}
    
  • Mercure: Use Stimulus actions to subscribe to updates:
    connect() {
        this.subscription = this.hub.subscribe('update', (event) => {
            this.element.textContent = event.data;
        });
    }
    

4. TypeScript Support

Enable TypeScript controllers by configuring assets/controllers.json:

{
    "controllers": [
        "./assets/controllers/**/*_controller.{js,ts}"
    ]
}

5. AssetMapper Configuration

Ensure assets/controllers.json excludes non-Stimulus files:

# config/packages/asset_mapper.yaml
framework:
    assets:
        excluded_patterns:
            - '*/controllers.json'

Advanced Patterns

1. Reusable Controllers

Create modular controllers in assets/controllers/ and import them in templates:

{{ stimulus_controller('shared/modal') }}

2. Parameterized Actions

Pass dynamic parameters to Stimulus actions:

{{ stimulus_action('modal#open', { 'id': post.id }) }}

Access in JavaScript:

open(event) {
    const id = event.detail.id; // post.id
}

3. Outlet Integration

Use outlets for parent-child controller communication:

<div {{ stimulus_controller('parent') }}>
    <div {{ stimulus_outlet('parent', 'child') }}></div>
</div>
// Parent controller
connect() {
    this.childController = this.outlet('child');
}

4. Debugging with Profiler

Enable Symfony Profiler to inspect Stimulus controllers:

# config/packages/dev/stimulus.yaml
stimulus:
    debug: true

Gotchas and Tips

Common Pitfalls

  1. Asset Pipeline Issues:

    • Symptom: Stimulus controllers not loading.
    • Fix: Verify assets/controllers.json is generated and included in your app.js:
      import './controllers/**/*_controller';
      
    • Debug: Check browser console for 404 errors on Stimulus JS files.
  2. Case Sensitivity in Parameters:

    • Issue: Parameters passed to stimulus_action are now camelCase (BC break in v2.13.0).
      {{ stimulus_action('example#action', { 'bigCrocodile': 'value' }) }}
      
      Access in JS as event.detail.bigCrocodile (not bigcrocodile).
  3. Windows Path Handling:

    • Issue: Stimulus controllers in subdirectories may fail on Windows.
    • Fix: Use forward slashes in controllers.json or configure AssetMapper to normalize paths.
  4. Twig Function Deprecations:

    • Issue: ux_controller_link_tags() was removed in v3.0.0 (requires AssetMapper >=6.4).
    • Fix: Use {{ stimulus_controller() }} directly or upgrade AssetMapper.
  5. TypeScript Module Conflicts:

    • Issue: type: "module" in package.json may break Stimulus imports.
    • Fix: Revert to "type": "commonjs" or ensure proper ESM imports:
      import { Controller } from '@hotwired/stimulus';
      

Debugging Tips

  1. Inspect Data Attributes: Use browser DevTools to verify rendered attributes:

    <div data-controller="example" data-example-target="modal">
    
  2. Log Stimulus Events: Add debug logs in controllers:

    connect() {
        console.log('Controller connected:', this.element.dataset);
    }
    
  3. Symfony Profiler: Enable Stimulus debugging in Profiler to track controller lifecycle:

    framework:
        profiler:
            collectors:
                stimulus: true
    
  4. AssetMapper Debugging: Check generated public/build/controllers.json for missing files:

    php bin/console assets:install
    

Extension Points

  1. Custom Twig Functions: Extend the bundle’s Twig environment:

    // src/Twig/Extension/StimulusExtension.php
    public function getFunctions() {
        return [
            new \Twig\TwigFunction('custom_stimulus', [$this, 'customStimulusFunction']),
        ];
    }
    
  2. Dynamic Controller Registration: Override the StimulusHelper service to customize attribute generation:

    # config/services.yaml
    Symfony\UX\StimulusBundle\Helper\StimulusHelper:
        arguments:
            $controllerNamespace: 'App\\Stimulus'
    
  3. Integration with Custom Packages: Use the StimulusBundle as a foundation to build domain-specific controllers (e.g., app/controllers/admin/*_controller.js).

Configuration Quirks

  1. PHP Version Compatibility:

    • Minimum: PHP 8.4 (v3.0.0+). Downgrade to v2.35 for PHP 8.2+.
    • Symfony: Requires Symfony 7.4+ (v3.0.0+). Use v2.35 for Symfony 6.4+.
  2. AssetMapper Exclusions: Ensure excluded_patterns in asset_mapper.yaml matches your project structure:

    framework:
        assets:
            excluded_patterns:
                - '*/controllers.json'  # Updated in v2.33
    
  3. NPM Dependency Conflicts:

    • Issue: Conflicts with stimulus package versions.
    • Fix: Pin versions in package.json:
      "dependencies": {
          "@hotwired/stimulus": "^3.2.1"
      }
      
  4. Caching Headaches:

    • Issue: Stimulus controllers not updating after changes.
    • Fix: Clear cache and rebuild assets:
      php bin/console cache:clear
      npm run build
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle