teamoping 2016-08-04 16:39:33 7099次浏览 1条评论 17 4 0

gridview插件被应用于数据呈现,它提供了很多功能,如浏览、排序、分页和数据过滤。

下面是一个简单的gridview应用实例

<?= GridView::widget([
     'dataProvider' => $dataProvider,
     'columns' => [
         'id',
         'name',
         'created_at:datetime',
         // ...
     ],
]) ?>

应用场景

对于gridview的一些详细用法,请看以下总结:

1.在例头添加排序,在cloumns中加入以下代码

['class' => 'yii\grid\SerialColumn']

2.列表勾选框,在cloumns中加入以下代码

['class' => 'yii\grid\CheckboxColumn'],

3.列数据快速格式化:时间戳转化为时间格式显示

'created_at:datetime',

4.显示关联表数据:前提是在model中有关联关系,例如:getAuthor()

'author.name', //获取关联表author的name的值

5.列表中显示图片:显示一张50*100的图片,label_img为图片地址

'label_img'=>[
    'label' => '标签图',
    'format' => [
        'image',
        [
            'height' =>50,
            'width' => 100
        ]
    ],
    'value' => function($model){
        return $model->label_img;
    }
],

6.显示状态,且带过滤

[
    'attribute' => 'is_valid',
    'label' => '发布状态',
    'value' => function($model) {
        return $model->is_valid == 0 ? '未发布' : '发布';
    },
    'filter' => [
        0 => '未发布',
        1 => '发布'
    ]
],

7.显示带html标签的例值:正常情况下是过滤html标签的

[
    'attribute' => 'content',
    'format' => 'raw',
    'value' => function ($model) { 
        return $model->content; 
    },
    
],

8.自定义按钮:{view} {update} {delete} 为默认,可以不填显示默认,也可以覆盖重新定义

[
    'class' => 'yii\grid\ActionColumn',
    'template' => '{test} {view} {update} {delete}',
    'header' => '操作',
    'buttons' => [
        'test' => function ($url, $model, $key) { 
            return Html::a('测试按钮', $url,['data-method' => 'post','data-pjax'=>'0'] ); 
        },
        'delete'=> function ($url, $model, $key){
            return  Html::a('删除', ['delete', 'id'=>$model->id],[
                'data-method'=>'post',              //POST传值
                'data-confirm' => '确定删除该项?', //添加确认框
            ] ) ;
        }
    ],
],

以上为gridview的一些基本操作,当然还有很多其他情景,但要活学活用,举一反三

觉得很赞
  • 评论于 2016-09-21 14:55 举报

    很实用。。。。
    如果再附上效果截图就更nice。。。。。。。。。。。。。

您需要登录后才可以评论。登录 | 立即注册