Ziyadin Shemsedinov
Ziyadin Shemsedinov

Reputation: 367

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

I have a custom column in 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'],
    ],
]); ?>

Upvotes: 3

Views: 7332

Answers (3)

sambua
sambua

Reputation: 2624

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

Upvotes: 0

Tony
Tony

Reputation: 5867

You lost your sort link because you are explicitly set 'header'=>'Sex' in your column configuration, remove it and sort link should appear.

Upvotes: 2

Beowulfenator
Beowulfenator

Reputation: 2300

I'll assume you're using 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. If you did everything right, your index.php file in views will contain an array of columns. 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.

Upvotes: 0

Related Questions