I have a Product admin class. The Product entity has a many-to-one relationship with a Category entity, i.e. a product is associated with a category.
In the admin "list" page for products, I need to sort by the category name (alphabetically) that each product is associated with.
Setting the default field to sort by is easy if the field is on the entity itself (see Sonata admin bundle order for how to do this). But I cannot figure out how to sort by a field in a related table.
Any help is appreciated.
It seems a workaround, but it works. You have to add a join overriding createQuery() method, than assign a default sortBy overriding $datagridValues:
Asume
name
is the property of entityCategory
by wich you want to sort. You may do this in youProductAdmin.php
This way you leverage the ordering links in the header of the list, generated by Sonata.
Edit
If you would also like to have a link on the category name in products list to quickly edit the
Category
entity, assuming you have created aCategoryAdmin
class, you should write your code like this:And in your
Category
class you should implement the__toString()
method like this: