Make Your Entities Sortable in EasyAdmin

JoliCode - JoliCodeBlog - 26/06
Imagine that your EasyAdmin administration backend contains an entity (Sponsor in our example) and that you want to give the user the possibility to choose the order in which these sponsors are displayed on the application frontend (maybe because alphabetical sorting is not relevant).

Imagine that your EasyAdmin administration backend contains an entity (Sponsor in our example) and that you want to give the user the possibility to choose the order in which these sponsors are displayed on the application frontend (maybe because alphabetical sorting is not relevant).

This article presents a simple implementation of this need, based on the Sortable Doctrine extension and EasyAdmin custom actions.

Section intitulée set-up-the-sortable-extensionSet up the Sortable extension

Thanks to the Doctrine Sortable extension, we will be able to store and update the position of our entity using $entity->setPosition($position), without worrying about updating the position of the other entities because the extension will manage it for us.

To use it, we must first require the StofDoctrineExtensionsBundle which will simplify the extension configuration.

composer require stof/doctrine-extensions-bundle

This generates a configuration file in which we need to declare the extension we want to enable.

# config/packages/stof_doctrine_extensions.yaml stof_doctrine_extensions: default_locale: en_US + orm: + default: + sortable: true

Section intitulée update-our-entityUpdate our entity

Now, we need to update our entity to add the property that will store its position. We can also add an index to this new property for performance purposes.

// src/Entity/Sponsor.php use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; #[ORM\Index(name: 'position_idx', columns: ['position'])] class...
[Courte citation de 8% de l'article original]
Loading...