Sort list view in Sonata Admin by related entity fields

别来无恙 提交于 2019-11-30 07:27:46

The next day after posting the question I was digging around the source code of SonataAdminBundle and Symfony and found the solution. It is actually very easy. Here it goes:

//...
->add(
    'state.country',
    null,
    array(
        'associated_property' => 'name', // property name of entity Country
        'sortable' => true, // IMPORTANT! make the column sortable
        'sort_field_mapping' => array(
            'fieldName' => 'name' // property name of entity Country
        ),
        'sort_parent_association_mappings' => array(
            array('fieldName' => 'state') // property state of entity City
            array('fieldName' => 'country') // property country of entity State
        )
    )
)
//...

With associated_property we set the property that should be displayed. This can be omitted if we have defined a __toString method in the entity. In this case it means the name of the country will be displayed in the column.

The option sort_field_mapping requires an array with the key fieldName holding the property by which we're sorting. Here we sort by the country's name. We could however sort by population, assuming we have that property in the entity Country, although we're displaying the value for the name.

And sort_parent_association_mappings is the most interesting part. Here we define the properties by which the join query should be created: City has a property state, which is the entity State, which itself has the property country being the entity Country.

I hope my explanation is comprehensible and can help other people too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!