Adding Stimulus Controllers

Since Contao 5 now uses Turbo and Stimulus for the backend, sometimes it might not be enough to register JS assets for the backend as described under Adding Backend assets, especially when listening for the DOMContentLoaded event.

Stimulus provides lifecycle callbacks for responding to these changes. Using it is optional, but it can help you manage initialization and cleanup as elements enter or leave the DOM.

The following example assumes:

  • You’re using Webpack Encore for asset management.
  • You want to add code for a custom widget.
Info

This guide is meant for bundle development.

Adding a custom Stimulus controller

// assets/controllers/my-custom-widget-controller.js
import { Controller } from '@hotwired/stimulus';

export default class MyCustomWidgetController extends Controller {
    connect() {
        // Initialize your widget here
    }
}

Adding your Stimulus application

// assets/backend.js
import { Application } from '@hotwired/stimulus';
import MyCustomWidgetController from './controllers/my-custom-widget-controller';

const application = Application.start();
application.register('my-vendor-prefix--my-custom-widget', MyCustomWidgetController);

Registering your Stimulus application

// package.json
{
  …
  "devDependencies": {
    "@hotwired/stimulus": "^3.2",
    // any other dependencies you need for your controller/application
  },
  …
}

Read more about developing Stimulus controllers here.

If your controller modifies the DOM or needs cleanup, see Turbo-compatible Stimulus controllers for notes on idempotency, disconnecting and Turbo’s cache.