Sort list view in Sonata Admin by related entity fields

前端 未结 1 352
北海茫月
北海茫月 2020-12-30 11:36

Using Sonata Admin Bundle, which is a great add-on for Symfony, I have bumped into the problem described as follows.

Let\'s say we have 3 entities: City, State and C

相关标签:
1条回答
  • 2020-12-30 12:05

    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.

    0 讨论(0)
提交回复
热议问题