Member-only story
Load Stimulus Controllers in Symfony EasyAdmin
I had the use case to enable drag and drop sorting in an EasyAdmin user interface. I want to reuse stimulus controllers I already coded on the Crud index page and take advantage of the simplicity of the Asset Mapper component.
Install Symfony and EasyAdmin
composer create-project symfony/skeleton:"7.2.x" my_project_directory
cd my_project_directory
composer require webapp
composer require easycorp/easyadmin-bundle
Boot Stimulus in the Admin
In order to dynamically load the Stimulus controller as you are used to, we must first create an entry point:
Path: assets/admin.js
import './bootstrap.js';
Add admin.js as entrypoint to your importmap.php in the project root
return [
'app' => [
'path' => './assets/app.js',
'entrypoint' => true,
],
'admin' => [
'path' => './assets/admin.js',
'entrypoint' => true,
],
Now we need to load the import map globally in EasyAdmin by overriding the EasyAdmin layout template:
Path: templates/bundles/EasyAdminBundle/layout.html.twig
{% extends '@!EasyAdmin/layout.html.twig' %}
{% block importmap %}
{{ parent() }}
{{ importmap('admin') }}
{% endblock %}
That’s it, now you can use all your Stimulus controllers in EasyAdmin!
Use a Stimulus Controller on a Crud index page
I use this Stimulus controller to enable sorting for a Crud Entity:
Path: assets/controllers/sortable_controller.js
import { Controller } from '@hotwired/stimulus';
import Sortable from 'sortablejs';
export default class extends Controller {
static values = {
url: String
}
connect() {
if (!this.element) return;
const tbody = this.element.querySelector('tbody');
if (!tbody) return;
new Sortable(tbody, {
animation: 150,
handle: '.drag-handle',
onEnd: this.onEnd.bind(this)
});
}
onEnd(event) {
const itemId = event.item.dataset.id;
const newPosition = event.newIndex + 1;
const oldPosition = event.oldIndex + 1;
fetch(this.urlValue.replace('{id}', itemId), {
method: 'POST'…