繁体   English   中英

如何在Yii 2中的GridView小部件中对自定义列进行排序?

[英]How to sort custom columns in GridView widget in Yii 2?

我在GridView中有一个自定义列。 实际上它是模型属性,但我需要自定义它以更方便的方式呈现数据。 如何添加对此列进行排序的功能?

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterPosition'=>  GridView::FILTER_POS_HEADER,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'username',
        'about:ntext',
         'birthdate',
        ['attribute'=>'sex',
         'header'=>'Sex',
         'content'=>  function($model){
          return $model->sex==0?'female':'male';  
         },
         'label'=>'Sex',
         'enableSorting'=>TRUE       

        ],

         'email:email',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

您丢失了排序链接,因为您在列配置中明确设置了'header'=>'Sex' ,将其删除并显示排序链接。

我假设您正在使用ActiveDataProvider

即使使用自定义函数显示属性,也会对存储在数据库中的实际属性进行排序。

尝试使用gii生成一组CRUD页面。 如果你做的一切正确, viewsindex.php文件将包含一个列数组。 然后你可以这样配置你的列:

        [
            'attribute' => 'myAttribute',
            'value' => function ($data) {
                return 'example'.' '.$data->myAttribute;
            }
        ],

显然,该函数需要做任何你需要的转换。 但是,将对存储在DB中的实际数据进行排序。

为了搜索性别,您可以轻松设置过滤器。 喜欢

   [
    'attribute'=> 'sex',
    # if you didn't set attribute in model or want different text use label
   'label' => 'Sex of person',
    # if you create it threw ModelSearch and there is attribute/field in one table gii will add automatically andFilterWhere method.
    'filter' => ['0' => 'Female', '1' => 'Male'],
   ],

对于更复杂的搜索/排序,这里是非常好的文档相关链接教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM