How to sort custom columns in GridView widgets in Yii 2?

I have a custom column in a GridView. This is actually a model attribute, but I needed to customize it to present the data in a more convenient way. How do I add a way 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'],
    ],
]); ?>

      

+3


source to share


3 answers


You have lost the sort reference because you explicitly set 'header'=>'Sex'

in the column configuration, remove it, and sort the reference.



+2


source


I assume you are using ActiveDataProvider

.

Even when you use a custom function to display an attribute, the sort is done on the actual attribute that is stored in the DB.

Try to create a set of CRUD pages with gii

. If you did everything correctly, your index.php

file views

will contain an array of columns. Then you can customize your column like so:



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

      

Obviously the function should do whatever conversions you want. But the sort will be done on the actual data stored in the DB.

0


source


It's easy to install a filter to find sex how

   [
    '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 complex searching / sorting here is some very good documentation linked to tutorial link

0


source







All Articles