Sonata admin - “order by” field in related table

后端 未结 2 745
北海茫月
北海茫月 2021-02-08 19:04

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

2条回答
  •  轮回少年
    2021-02-08 19:39

    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();
    }
    

提交回复
热议问题