4
votes

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);
...
}
1
update your question and add your related ModelSearch code .. please - ScaisEdge
Of course but as I said, if I'm using setSort, then all other attributes stop sorting and I would have to define all other attributes also ince again. The question is, if there is a built-in solution to add a new attribute to Sort next to the existing ones. - user2511599
In your code i don't see any "virtual/related" attribute and any setSort .. .. please show the minimal (consistent) code relate to you question .. - ScaisEdge

1 Answers

5
votes

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,
                ];