Sorting select fields in EasyAdminBundle

  • You are here: Free PHP » Uncategorized » Sorting select fields in EasyAdminBundle

I'm currently working on an application using Symfony and their EasyAdminBundle. The experience has been great overall, although there are lots of details and specific usecases that are hard to figure out.

For instance when using relations in your entities and creating the related forms. Select fields for related entities are by default sorted by the key (usually the ID of the related entity), however you'd usually want to sort it alphabetically by the name of the entity. My initial thought was to use the @OrderBy annotation, however that only works for the actual OneToMany relations on the other side of the relation, not on the selectbox for the ManyToOne side of the relation. So that was quickly discarded.

Next up I found that you can do it in Symfony by specifying a query_builder parameter to your form configuration. The downside here is that by default, EasyAdminBundle works with a yaml configuration for your form so that makes it a lot harder to do this. I could do this in an extended AdminController, but that would mess with my form field order.

Eventually, however, I found this comment on Github that gave me the solution. Instead of specifying an anonymous function, you can also specify a static method to be called to fetch the values. And so, my solution was now easily implemented.

In my YAML file, I could now specify the query_builder parameter:

- { property: supplier, label: 'Leverancier', type_options: { 'query_builder': 'App\Repository\SupplierRepository::getSuppliersForSelect' } }

In said repository, I added the specified static method:

    static public function getSuppliersForSelect(EntityRepository $entityRepository)
    {
        return $entityRepository
            ->createQueryBuilder('s')
            ->orderBy('s.name', 'ASC');
    }

and now my select field has a nicely alphabetically sorted list of suppliers.

Powered by Gewgley