刚开始接触yii2时,利用gii生成了一个列表,里面只有很简短的几句,不用foreach循环,就可以查询出多条数据,感觉好神奇,通知接下来的不断摸索,终于掌握了gridview的大多数功能,现分享如下:
一、gridview与搜索功能很好的结合在了一起,先讲不带搜索的使用
控制器中,代码很简单,与gii生成的代码一样
use yii\data\ActiveDataProvider; public function actionList(){ $where['status'] = Table::STATUS_NORMAL; $model= new ActiveDataProvider([ //后面的query可以跟with,joinwith等 'query' => Table::find()->where($where)->orderBy('id desc'), 'pagination' => [ 'pageSize' => 10, ], ]); return $this->render('list',[ 'model' => $model, ]); }
视图:
<?php use common\widgets\LinkPager; //跳转页的扩展 use business\assets\AppAsset; use yii\bootstrap\ActiveForm; use yii\grid\GridView; ?> <?php echo GridView::widget([ 'dataProvider' => $model, //不带查询的就只有这一句 'layout' => "{items}\n{pager}", //去掉之后,后显示总共多少页,当前处于什么位置 'filterSelector' => "input[name='".$model->getPagination()->pageParam."']",//去掉之后,跳转分页失效 'pager' => [ 'class' => LinkPager::className(), 'firstPageLabel' => '第一页', 'lastPageLabel' => '最后一页', 'prevPageLabel' => '上一页', 'nextPageLabel' => '下一页', ], 'columns' => [ ['class' => 'yii\grid\CheckboxColumn'],//复选框列 // ['class' => 'yii\grid\SerialColumn'],//序号从1自增长 'id', 'tablename', ['label'=>'状态','value'=>function($model){ return empty($model->area->areaname)? "区域已被删除":$model->area->areaname; }], 'tableType.name', 'seatingfee', 'employee.username', [ 'class' => 'yii\grid\ActionColumn', 'header' => '操作', 'template' => '{view} {delete} {look}', //跟下面的三个操作要一致 'buttons' => [ 'view' => function($url, $model) { return Html::a('编辑','javascript:void(0)',['class' => 'edit','data-tableid'=>$model->id ]); }, 'delete' => function($url, $model){ return Html::a('删除','javascript:void(0)',['class' => 'del','data-tableid'=>$model->id ]); }, 'look' => function($url, $model){ return Html::a('查看二维码','javascript:void(0)',['class' => 'look','data-url'=>"http://xiaochengfu.com/Table/sweep/index?tableid=$model->id&storeid=$model->storeid",'data-tableid'=>$model->id,'data-storeid'=>$model->storeid]); }, ], ], ], ]); ?>
注意:此页面效果如下:注意代码中和下图注释的内容
二、这里重点说一下columns里面的内容,这里可以自定义的比较多,可以添加查询、全选、在列表中直接修改内容等
这里我整理了一些可以自定义的内容:
'columns' => [ [ 'class' => 'yii\grid\CheckboxColumn', 'name'=>'id', ],//复选框列 'id', 'type:boolean',//显示是或否 'addtime:dateTime',//显示时间信息 ['label'=>'菜品图片', 'format' => [ 'image', [ 'width'=>'50', 'height'=>'50' ] ], 'value' => function ($model) { return Url::toCover($model->picture); } ], //将图片放到列表中,可定义宽度高度 ['label'=>'商品类型','value'=>function($model){ return $model->type == 1 ? '单品' : '套餐'; }], [ 'attribute' => 'cateid', 'headerOptions' => ['class' => 'col-md-1'], 'filterInputOptions' => ['class' => 'form-control input-sm'], 'value' => function ($model) { //这里可以写if判断 return $model->category->catename; } ], [ 'attribute' => 'created_at', 'format' => ['date', 'php:Y-m-d H:i'], 'headerOptions' => ['class' => 'col-md-3'], 'value' => function ($model) { return $model->created_at; }, ], ],
不带查询的gridview差不多就这些,下一篇会介绍带查询的各种使用方法!