phpsortinggridviewyii2virtual-attribute

Yii2 add related attribute to sort


I have normal ModelSearch with ActiveDataProvider, and I would like to add a virtual/related attribute to sorting in gridview. If I'm doing with setSort, and I'm adding this only attribute, then all other attributes are not sortable any more. Is there a built-in way to add an attribute to Sort? Thanks a lot!

public function search($params) {
    $query = Za::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder' => ['aonr' => SORT_ASC]],
        'pagination' => [
            'pageSize' => 15,
        ],
    ]);

$dataProvider->setSort([
    'attributes' => [
        'lwnr' => [
            'asc' => ['lwnr' => SORT_ASC],
            'desc' => ['lwnr' => SORT_DESC],
            'label' => 'lwnr',
            'default' => SORT_DESC,
        ],
    ]
]);

$this->load($params);
...
}

Solution

  • You can set the sortable attributes with the setSort method, but in this case you need to set all the columns you want to sort, not just the column from the relation.

    If you want to add one column you can try this (merging the currently existing sort attributes with the new one):

        $dataProvider->setSort([
            'attributes' => array_merge(
                $dataProvider->getSort()->attributes,
                [
                    'lwnr' => [
                        'asc'     => ['lwnr' => SORT_ASC],
                        'desc'    => ['lwnr' => SORT_DESC],
                        'label'   => 'lwnr',
                        'default' => SORT_DESC,
                    ],
                ]
            ),
        ]);
    

    or you can add the missing attributes/columns by hand (which is a far better idea)

        $dataProvider->setSort([
            'attributes' =>
                [
                    'lwnr' => [
                        'asc'     => ['lwnr' => SORT_ASC],
                        'desc'    => ['lwnr' => SORT_DESC],
                        'label'   => 'lwnr',
                        'default' => SORT_DESC,
                    ],
                    // Other attribute
                    'id'   => [
                        'asc'  => ['id' => SORT_ASC],
                        'desc' => ['id' => SORT_DESC],
                    ],
                    ...
                ],
        ]);
    

    Another way:

    $dataProvider->getSort()->attributes['lwnr'] = [
                        'asc'     => ['lwnr' => SORT_ASC],
                        'desc'    => ['lwnr' => SORT_DESC],
                        'label'   => 'lwnr',
                        'default' => SORT_DESC,
                    ];