<?php
$this->widget('zii.widgets.grid.CGridView', [
'id' => 'words-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => [
// 1. 複選框列 (支援批次操作)
[
'class' => 'CCheckBoxColumn',
'htmlOptions' => ['width' => '30px'],
'selectableRows' => 2, // 允許多選
'checkBoxHtmlOptions' => ['name' => 'selected_ids[]'], // 表單提交名稱
],
'zw_id',
'zw_title',
// 2. 資料轉換顯示
[
'name' => 'zw_level',
'value' => 'Words::model()->getLevel($data->zw_level)',
'filter' => Words::model()->getLevelOptions(), // 下拉過濾
],
'zw_replaceword',
'zw_listorder',
// 3. 日期格式化
[
'name' => 'inputtime',
'value' => 'date("Y-m-d", $data->inputtime)',
'htmlOptions' => ['style' => 'text-align:center'],
],
// 4. 按鈕列控制
[
'class' => 'CButtonColumn',
'buttons' => [
'view' => [
'visible' => 'false', // 隱藏檢視按鈕
],
'update' => [
'label' => '編輯',
'imageUrl' => Yii::app()->baseUrl . '/images/edit.png',
],
'delete' => [
'visible' => '$data->zw_id > 10', // 條件顯示
'click' => 'function(){ return confirm("確定刪除?"); }',
],
],
'template' => '{update} {delete}',
],
],
]);
?>
檔案:`framework/zii/widgets/grid/CGridView.php` 第 152 行左右
public function renderFooterCell() {
if (trim($this->footer) !== '') {
echo CHtml::openTag('td', $this->footerHtmlOptions);
$this->renderFooterCellContent();
echo '</td>';
}
}
<?php
namespace app\components;
class GridView extends \zii\widgets\grid\CGridView {
public function renderFooterCell() {
if (trim($this->footer) !== '') {
echo CHtml::openTag('td', $this->footerHtmlOptions);
$this->renderFooterCellContent();
echo '</td>';
}
}
}
?>
<?php
$this->widget('app\components\GridView', [
'columns' => [
[
'class' => 'CCheckBoxColumn',
'footer' => '<button onclick="deleteAll()">批次刪除</button> <button onclick="refreshAll()">重新整理</button>',
'footerHtmlOptions' => ['colspan' => 5, 'style' => 'text-align:left'],
'selectableRows' => 2,
],
// 其他欄位...
],
]);
?>
<script>
function deleteAll() {
var ids = [];
$('#words-grid input[name="selected_ids[]"]:checked').each(function() {
ids.push($(this).val());
});
if (ids.length === 0) { alert('請選擇資料'); return; }
if (!confirm('確定刪除 ' + ids.length + ' 筆資料?')) return;
$.post('/admin/words/batchDelete', { ids: ids }, function(res) {
if (res.success) $.fn.yiiGridView.update('words-grid');
else alert(res.message);
}, 'json');
}
function refreshAll() {
$.fn.yiiGridView.update('words-grid');
}
</script>
| 需求 | 解決方案 |
|---|---|
| 欄位排序開關 | `'enableSorting' => false` |
| 欄位隱藏/顯示權限控制 | `'visible' => Yii::app()->user->checkAccess('admin')` |
| 自訂搜尋下拉選單 | `'filter' => ['1'=>'啟用','0'=>'停用']` |
| 列點擊跳轉 | `'selectionChanged' => 'function(id){ location.href="/view/"+id; }'` |
| 自訂 CSS 類別 | `'itemsCssClass' => 'table table-striped table-hover'` |
| 固定欄寬 | `'htmlOptions' => ['width' => '120px']` / `'headerHtmlOptions'` |