首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii2 GridView 常見操作大全(含官方文件補充)

     編輯:PHP 綜合知識

欄位顯示控制

// 條件顯示
['attribute' => 'name', 'visible' => Yii::$app->request->get('type') == 1],

// 連結欄位
[
    'attribute' => 'order_id',
    'value' => fn($m) => Html::a($m->order_id, ['order/view', 'id' => $m->order_id], ['target' => '_blank']),
    'format' => 'raw',
],

// 圖片欄位
[
    'label' => '頭像',
    'format' => ['image', ['width' => 84, 'height' => 84]],
    'value' => 'avatar_url',
],

// HTML 渲染
[
    'attribute' => 'content',
    'value' => 'content',
    'format' => 'html', // 或 'raw'
],

操作欄自訂

[
    'class' => 'yii\grid\ActionColumn',
    'template' => '{view} {update} {custom}',
    'buttons' => [
        'custom' => fn($url, $model) => Html::a('自訂', $url, [
            'class' => 'btn btn-xs btn-info',
            'onclick' => "customAction({$model->id}); return false;",
        ]),
    ],
],

樣式與寬度

[
    'attribute' => 'title',
    'headerOptions' => ['width' => '300'],
    'contentOptions' => ['style' => 'white-space: nowrap; text-overflow: ellipsis; overflow: hidden;'],
],

列表樣式交替

 $dataProvider,
    'rowOptions' => fn($model, $key, $index) => ['class' => $index % 2 ? 'odd' : 'even'],
    'columns' => [...],
]); ?>

官方文件補充:GridView 核心屬性

屬性說明
dataProvider資料提供者(ActiveDataProvider/SqlDataProvider/ArrayDataProvider)
filterModel搜尋模型,啟用欄位過濾列
columns欄位設定陣列,支援字串、陣列、閉包、類別名稱
layout版面配置:{summary}{items}{pager}
pager分頁元件設定(LinkPager 預設)
sorter排序元件設定
caption表格標題(輸出 <caption>)
tableOptionstable 標籤屬性,如 ['class' => 'table table-striped']

DataColumn 格式化速查

format 支援:raw、html、text、ntext、date、time、datetime、email、image、url、boolean、size(Bytes 可讀)、currency。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved