![](/img/trans.png)
[英]How to control the number of gridview widget columns dynamically in Yii2?
[英]How to sort custom columns in GridView widget in Yii 2?
我在GridView中有一個自定義列。 實際上它是模型屬性,但我需要自定義它以更方便的方式呈現數據。 如何添加對此列進行排序的功能?
<?= 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'
,將其刪除並顯示排序鏈接。
我假設您正在使用ActiveDataProvider
。
即使使用自定義函數顯示屬性,也會對存儲在數據庫中的實際屬性進行排序。
嘗試使用gii
生成一組CRUD頁面。 如果你做的一切正確, views
的index.php
文件將包含一個列數組。 然后你可以這樣配置你的列:
[
'attribute' => 'myAttribute',
'value' => function ($data) {
return 'example'.' '.$data->myAttribute;
}
],
顯然,該函數需要做任何你需要的轉換。 但是,將對存儲在DB中的實際數據進行排序。
為了搜索性別,您可以輕松設置過濾器。 喜歡
[
'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'],
],
對於更復雜的搜索/排序,這里是非常好的文檔相關鏈接教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.