use yii\grid\GridView;
use yii\helpers\Html;
echo GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'], // 序號列
// 字段列
'name',
'population',
// 自定義值列
[
'attribute' => '測試字段',
'value' => function ($model) { return 'abc'; }
],
// 內置操作列 (查看/更新/刪除)
['class' => 'yii\grid\ActionColumn', 'header' => '操作'],
// 完全自定義按鈕列
[
'label' => '更多操作',
'format' => 'raw', // 輸出原始 HTML
'value' => function ($model) {
$url = "https://www.baidu.com";
return Html::a('添加權限組', $url, [
'title' => '審核',
'class' => 'btn btn-xs btn-primary',
'target' => '_blank',
]);
}
],
],
]);
| 屬性 | 作用 | 示例 |
|---|---|---|
| label | 列頭顯示文本 | '更多操作' |
| format | 輸出格式 | 'raw'(HTML), 'text', 'html', ['date','php:Y-m-d'] |
| value | 單元格內容 | 匿名函數接收 $model,$key,$index,$column |
| headerOptions | 表頭單元格屬性 | ['style'=>'width:120px;'] |
| contentOptions | 內容單元格屬性 | ['class'=>'text-center'] |
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'template' => '{view} {update} {delete} {custom}', // 自定義模板順序
'buttons' => [
'custom' => function ($url, $model, $key) {
return Html::a('', $url, [
'title' => '自定義操作',
'data-pjax' => '0',
]);
},
],
'urlCreator' => function ($action, $model, $key, $index) {
// 統一 URL 生成邏輯
return \yii\helpers\Url::toRoute([$action, 'id' => $key]);
},
'visibleButtons' => [
'delete' => function ($model, $key, $index) {
return $model->status !== 'locked'; // 條件顯示
},
],
]
[
'class' => 'yii\grid\ActionColumn',
'buttons' => [
'delete' => function ($url, $model, $key) {
return Html::a('', $url, [
'title' => '刪除',
'data-confirm' => '確定要刪除嗎?',
'data-method' => 'post',
'data-pjax' => '0',
]);
},
],
]
// CSS 響應式
.table-responsive { overflow-x: auto; }
// GridView 容器
echo '';
echo GridView::widget([...]);
echo '';
// 列顯示控制
'columns' => [
[
'attribute' => 'description',
'visible' => !Yii::$app->request->isMobile, // 移動端隱藏長文本
],
]
GridView 是 Yii 2.0 後台開發的核心組件,掌握列定義、按鈕自定義、條件顯示三大能力,即可構建功能豐富、體驗優雅的數據管理界面。