简体   繁体   English

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

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

I have a custom column in GridView. 我在GridView中有一个自定义列。 Actually it's model attribute but I needed to customize it for presenting data in more convenience way. 实际上它是模型属性,但我需要自定义它以更方便的方式呈现数据。 How to add an ability to sort this column? 如何添加对此列进行排序的功能?

<?= 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' ,将其删除并显示排序链接。

I'll assume you're using ActiveDataProvider . 我假设您正在使用ActiveDataProvider

Even when you use a custom function to display the attribute, the sorting is done on the actual attribute that is stored in the DB. 即使使用自定义函数显示属性,也会对存储在数据库中的实际属性进行排序。

Try generating a set of CRUD pages using gii . 尝试使用gii生成一组CRUD页面。 If you did everything right, your index.php file in views will contain an array of columns. 如果你做的一切正确, viewsindex.php文件将包含一个列数组。 Then you can configure your column like so: 然后你可以这样配置你的列:

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

Obviously, the function needs to do whatever transformations you need. 显然,该函数需要做任何你需要的转换。 But the sorting will be done on the actual data stored in the DB. 但是,将对存储在DB中的实际数据进行排序。

For searching sex it's easy you can set filter. 为了搜索性别,您可以轻松设置过滤器。 Like 喜欢

   [
    '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'],
   ],

For more complicated search/sort here is very good documentation related link to tutorial 对于更复杂的搜索/排序,这里是非常好的文档相关链接教程

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

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