Sonata admin - "order by" field in related table Sonata admin - "order by" field in related table symfony symfony

Sonata admin - "order by" field in related table


It seems a workaround, but it works. You have to add a join overriding createQuery() method, than assign a default sortBy overriding $datagridValues:

<?phpuse Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;class ExpenseAdmin extends Admin{    protected $datagridValues = array(        '_page'       => 1,        '_sort_order' => 'ASC', // sort direction        '_sort_by' => 'c.name' // field name    );    /**     * @return \Sonata\AdminBundle\Datagrid\ProxyQueryInterface     */    public function createQuery($context = 'list')    {        $query = parent::createQuery($context);        return new ProxyQuery($query            ->join(sprintf('%s.category', $query->getRootAlias()), 'c'));    }}


Asume name is the property of entity Category by wich you want to sort. You may do this in you ProductAdmin.php

protected function configureListFields(ListMapper $listMapper){     $listMapper->add('category.name', null, array(            'sortable' => true,     ));     ...}

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 a CategoryAdmin class, you should write your code like this:

protected function configureListFields(ListMapper $listMapper){     $listMapper->add('category', null, array(            'sortable' => 'category.name',     ));     ...}

And in your Category class you should implement the __toString() method like this:

public function __toString(){    return $this->getName();}