给Yii2-GridView非模型中的字段增加排序功能
时间: 2024-03-01 22:53:53 浏览: 114
在Yii2-GridView中,如果要给非模型中的字段增加排序功能,可以使用`dataProvider`的`sort`属性来实现。具体步骤如下:
1. 在`GridView`的`dataProvider`属性中添加`sort`属性,如下所示:
```php
$dataProvider = new ArrayDataProvider([
'allModels' => $models,
'sort' => [
'attributes' => ['non_model_field'],
],
]);
```
2. 在`GridView`的`columns`属性中添加对应的排序列,如下所示:
```php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
'non_model_field',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
```
3. 最后,需要在非模型的字段中实现排序功能。可以在`dataProvider`的`query`属性中添加排序规则,如下所示:
```php
$dataProvider = new ArrayDataProvider([
'allModels' => $models,
'sort' => [
'attributes' => ['non_model_field'],
],
'query' => function ($models) {
$sort = Yii::$app->request->getQueryParam('sort');
if ($sort && isset($sort['non_model_field'])) {
$direction = strtolower($sort['non_model_field']) == 'desc' ? SORT_DESC : SORT_ASC;
usort($models, function($a, $b) use ($direction) {
return $direction * ($a['non_model_field'] <=> $b['non_model_field']);
});
}
return $models;
},
]);
```
以上就是在Yii2-GridView中给非模型中的字段增加排序功能的方法。
阅读全文