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'],
],
]); ?>
source to share
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.
source to share
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
source to share