[ 'header' => '操作', 'class' => 'yii\grid\ActionColumn', 'template' => '{view} {update} {delete} {abc}', //{view} {update} {delete}系统定义的,{abc}自定义的 'buttons' => [ 'view' => function ($url, $model, $key) { //$url是系统定义的三个操作的url,$model为数据对象,$key为循环的键值(用处不大) return $key == 1 ? null : \common\components\MyHelper::mybutton('/xx/xx?id=' . $key, 'view', ['title' => '标签的title属性']); }, 'delete' => function ($url, $model, $key) { return $key == 1 ? null : \common\components\MyHelper::mybutton($url, 'delete'); }, 'abc'=>function(){return '<a>abc</a>';} ] ],
MyHellper代码如下:
/** * 生成操作按钮 * @param $url * @param string $type * @param array $options * @return string */ public static function mybutton($url, $type = 'update', $options = []) { if ($type == 'view') { return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, ArrayHelper::merge([ 'title' => Yii::t('yii', 'View'), 'data-pjax' => '0', ], $options)); } if ($type == 'update') { return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, ArrayHelper::merge([ 'title' => Yii::t('yii', 'Update'), 'data-pjax' => '0', ], $options)); } if ($type == 'delete') { return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, ArrayHelper::merge([ 'title' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'post', 'data-pjax' => '0', ], $options)); } }
完整的GridView写法
<?= \yii\grid\GridView::widget([ 'dataProvider' => $dataprovider, 'filterModel' => $searchmodel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'],//生成序列号 'id', // 直接显示字段
'name:text:名称', //name字段的内容格式化为定义的text类型,表头内容设置为“名称” [ 'attribute'=>'field', // 关联的字段名 'filter'=>['1'=>'x','2'=>'y','3'=>'z'], // 这会生成一个select下拉框(<option value="1">x</option>)的查询字段 ], [ 'header' => '表头th中显示的内容', 'content' => function ($data) { // $data为循环变量 //...一些处理代码 return $content; // 返回要显示的内容,无查询框 } ], [ 'label'=>'链接', // 表头th中内容,有header时,优先显示header的内容 'value'=>function($data){return Url::to('controller/action');}, // 要显示的列表项内容,优先显示content内容 'filter'=>'', // 为空表示不显示查询框 'headerOptions' => ['width' => '250'], // 可以添加标签属性 ], 'time:datetime', // format属性简写方式如:['format'=>'text'] ], ]) ?>
详细的gridview用法可以参考:http://www.yiichina.com/doc/api/2.0/yii-grid-gridview