3

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'],
    ],
]); ?>
1
  • The problem is: you always sort data on database side. Please provide more information (source code) about that custom column/attribute. Commented Jun 20, 2015 at 20:50

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, man. By some reason, I thought that it it's mandatory to set header.
0

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.

1 Comment

Yes, I'm using ActiveDataProvider and crud pages I generated crud pages by gii. But after customization of column the sort link in header lost, I just want this sorting link in header cell back. I added code of widget to question.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.