CGridView 是 Yii 內建最強大的數據表格控件,善用它能大幅減少後台管理開發量。本文以 Blog Demo 為例,從基礎到進階全面講解。
// views/post/admin.php
$this->widget('zii.widgets.grid.CGridView', [
'id' => 'post-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => [
'post_id', 'title', 'content', 'tags', 'status',
'create_time', 'update_time', 'author_id', 'is_delete',
['class' => 'CButtonColumn'], // 默認:查看/更新/刪除
],
]);
dataProvider 來自 Model 的 search() 方法(返回 CActiveDataProvider),filter 啟用列頭過濾輸入框。
'columns' => [
// 簡單字段
'post_id',
'title',
// 格式化顯示:is_delete 0/1 → 否/是
[
'name' => 'is_delete',
'value' => '$data->is_delete ? "是" : "否"', // PHP 表達式,$data 為當前行模型
'filter' => ['0' => '否', '1' => '是'], // 下拉過濾
'htmlOptions' => ['class' => 'delete-col'], // td class
],
// 關聯字段顯示:作者姓名
[
'name' => 'author_name', // 虛擬屬性名
'value' => '$data->author->username',
],
// 自定義純文本列
[
'header' => '備註',
'value' => 'display your data',
],
['class' => 'CButtonColumn'],
],
[
'class' => 'CCheckBoxColumn',
'selectableRows' => 2, // 0=禁用, 1=單選, 2=多選
'headerHtmlOptions' => ['width' => '18px'],
'checkBoxHtmlOptions' => ['name' => 'post_ids[]', 'class' => 'row-select'],
],
配合 JS 可實現批量操作(刪除、發布等)。
[
'class' => 'CButtonColumn',
'template' => '{view} {update}', // 僅保留查看、更新
],
[
'class' => 'CButtonColumn',
'template' => '{view} {update} {print}',
'buttons' => [
'print' => [
'label' => '打印',
'url' => 'Yii::app()->controller->createUrl("print", ["id" => $data->post_id])',
'options' => ['target' => '_blank', 'class' => 'btn-print'],
],
],
],
$js = <<widget('zii.widgets.grid.CGridView', [ 'afterAjaxUpdate' => $js, // ... ]);
class Post extends CActiveRecord {
public $author_name; // 搜索用虛擬字段
// ...
}
public function search() {
$criteria = new CDbCriteria;
$criteria->with = ['author']; // 急切加載關聯
$criteria->compare('post_id', $this->post_id);
// ...
$criteria->compare('author.username', $this->author_name, true); // 模糊搜索用戶名
return new CActiveDataProvider($this, ['criteria' => $criteria]);
}
[
'name' => 'author_name',
'value' => '$data->author->username',
'filter' => CHtml::activeTextField($model, 'author_name'), // 關鍵:渲染搜索框
],
public function rules() {
return [
// ...
['post_id, title, ..., author_name', 'safe', 'on' => 'search'], // 必須加入 author_name
];
}
search() 中 criteria->compare 實現搜索。with 急切加載 → compare('關聯表.字段') → rules() 加入虛擬屬性 safe。afterAjaxUpdate 解決 AJAX 翻頁/搜索後 JS 事件失效問題。熟練掌握 CGridView,後台列表開發效率可提升 80% 以上。