[gridview] -- 超详细使用

原文地址 : https://segmentfault.com/a/1190000006868819


Yii2 GridView是实现yii网格视图的小部件,一般用于报表视图的展示。今天,结合DataProvider(ArrayDataProvider以及SqlDataProvider)说一下GridView中的几个Columns(SerialColumn,DataColumn,ActionColumn)。

教程一 

1.页面显示的时间戳转换
a.

[
        'label'=>'创建日期',
        'attribute' => 'created_at',
        'filter' => false, //不显示搜索框
        'value' => function($data) {
               return date('Y-m-d H:i:s',$data->created_at); }
],

b.

[
        'label'=>'创建日期',
        'attribute' => 'created_at',
        'format' => ['date', 'php:Y-m-d H:i:s'],
],

2.为字段加超链接

[ 
      'attribute'=>'title’,
      'format'=>'raw’,
      'value'=> function($data){return Html::a($data->title,['exam/index', 
            'id' => $data->_id],['title' => '审核']);} 
],

[
     'label'=>'更多操作’, 
     'format'=>'raw’,
     'value' => function($data) { 
           $url = "http://www.baidu.com”; 
           return Html::a('添加权限组', $url, ['title' => '审核']); } 
],

3.下拉菜单搜索

[
            'label' => '当前状态',
            'attribute' => 'status',
            'filter' => Html::dropDownList('AppBaseSearch[status
]',$searchModel-> status,
                    [ '' => '请选择',
                    ‘0' => '审核拒绝', 
                    ‘1' => '审核通过', 
		]),

     'value' => function($date) {
                    switch ($date-> status) {
                        case 1';
                            return '审核通过';
                            break;
                        case ‘0';
                            return '审核拒绝';
                            break;
                        default:
                            return '未知状态';
                            break;
                    }
                }
            ],

4.私人定制增删改按钮

[
                'header' => "查看/审核",
                'class' => 'yii\grid\ActionColumn',
                'template'=> '{view} {update} {delete}',
                'headerOptions' => ['width' => '140'],
                'buttons' => [
                    'view' => function ($url, $model, $key) {
                        return Html::a(Html::tag('span', '', ['class' => "glyphicon fa fa-eye"]), ['admin/view-app', 'id'=>$model->app_id], ['class' => "btn btn-xs btn-success", 'title' => '查看']);
                    },
                    'update' => function ($url, $model, $key) use($uid){
                          return Html::a('通过', ['admin/reviewapp','id'=>$model->app_id, 'status’=>1], ['class' => "btn btn-xs btn-info"]);
                    },
                    'delete' => function ($url, $model, $key) {
                            return Html::a('拒绝', ['admin/reviewapp', 'id' => $model->app_id, 'status’=>0], ['class' => "btn btn-xs btn-danger"]);
                    }
                ]
],

教程二

1. SerialColumn

SerialColumn就是连续的列,主要用于网格的行号,属于自增式的列。用法很简单:

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'], // 连续编号
        // 其他数据列和操作列
    ]
]);

展示结果:

#
1
2

2. DataColumn

DataColumn主要展示数据的,所有跟数据有关的展示基本都在这个Column中实现。因此用法也很多,但是有一条,如果对数据不做处理,那么字段必须是ArrayDataProvider对象的allModels的二维数组的key或者是SqlDataProvider对象sql查询结果二维数组的key。

用法一:表头即字段名,首字母大写

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'orderNo',   //订单编号
        'username'   // 用户名
    ]
]);

展示结果:

OrderNo Username
123345698763 Test用户
236479547829 Joyven

用法二:定义表头并格式化数据

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'time:date:日期',
        'pv:raw:PV',
        'uv:raw:UV',
    ]
]);

展示结果:

日期 PV UV
2016年9月10日 8500 6384
2016年9月9日 8378 6523

用法三:数据过滤,classattributelabelformat均不是必须要的。class默认是yii\grid\DataColumnattribute是指定排序的字段key,一定是dataProvider中提供的数据的key,如果不指定,对于过滤的数据,不能点击表头排序。

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        [
        'value' => function($data) {
            if (isset($data['time'])) {
                return date('Y-m-d', $data['time']);
            }
        },
        'attribute' => 'time', //用于排序,如果不写,不能点击表头排序,非必须
        'label' => '日期', // 自定义表头,非必须
        'format' => 'raw', // 格式方式,非必须
        ],
        'pv:raw:PV',
        [
        'class' => 'yii\grid\DataColumn',
        'value' => function ($data) {
            if (isset($data['orderCr'])) {
                return ($data['orderCr'] * 100) . '%';
            }
        },
        'attribute' => 'orderCr',
        'label' => '下单转化率',
        'format' => 'raw',
    ],
    ]
]);

关于format支持的格式:

format 说明 参数 返回 备注
raw Formats the value as is without any formatting. This method simply returns back the parameter without any format.The only exception is a nullvalue which will be formatted using [[nullDisplay]]. @param mixed $value the value to be formatted. @return string the formatted result. -
text Formats the value as an HTML-encoded plain text. @param string $value the value to be formatted. @return string the formatted result. -
ntext Formats the value as an HTML-encoded plain text with newlines converted into breaks. @param string $value the value to be formatted. @return string the formatted result. -
html Formats the value as HTML text.The value will be purified using [[HtmlPurifier]] to avoid XSS attacks.Use [[asRaw()]] if you do not want any purification of the value. @param string $value the value to be formatted.@param array or null $config the configuration for the HTMLPurifier class. @return string the formatted result. -
date Formats the value as a date. @param integer or string or DateTime $value the value to be formatted. The following types of value are supported: 1.an integer representing a UNIX timestamp; 2.a string that can be parsed to create a DateTime object.The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given; 3.a PHP DateTimeobject @param string $format the format used to convert the value into a date string.If null, [[dateFormat]] will be used. This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.It can also be a custom format as specified in the ICU manual.Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function. @return string the formatted result. @throwsInvalidParamException if the input value can not be evaluated as a date value. @throwsInvalidConfigException if the date format is invalid.
time Formats the value as a time. @param integer or string or DateTime $value the value to be formatted. The following types of value are supported:1. an integer representing a UNIX timestamp; 2. a string that can be parsed to create a DateTime object.The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given; 3. a PHP DateTimeobject @param string $format the format used to convert the value into a date string.If null, [[timeFormat]] will be used.This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.It can also be a custom format as specified in the ICU manual.Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function. @return string the formatted result. @throwsInvalidParamException if the input value can not be evaluated as a date value. @throwsInvalidConfigException if the date format is invalid.@seetimeFormat
paragraphs Formats the value as HTML-encoded text paragraphs.Each text paragraph is enclosed within a

 tag.One or multiple consecutive empty lines divide two paragraphs.

@param string $value the value to be formatted. @return string the formatted result. -
email Formats the value as a mailto link. @param string $value the value to be formatted. @param array $options the tag options in terms of name-value pairs. See [[Html::mailto()]]. @return string the formatted result. -
image Formats the value as an image tag. @param mixed $value the value to be formatted. @param array $options the tag options in terms of name-value pairs. See [[Html::img()]]. @return string the formatted result. -
url Formats the value as a hyperlink. @param mixed $value the value to be formatted. @param array $options the tag options in terms of name-value pairs. See [[Html::a()]]. @return string the formatted result. -
boolean Formats the value as a boolean. @param mixed $value the value to be formatted. @return string the formatted result. @seebooleanFormat -
datetime Formats the value as a datetime. @param integer or string or DateTime $value the value to be formatted. The following types of value are supported: 1. an integer representing a UNIX timestamp; 2. a string that can be parsed to create a DateTime object. The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.; 3. a PHP DateTime object @param string $format the format used to convert the value into a date string. If null, [[dateFormat]] will be used. This can be "short", "medium", "long", or "full", which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual. Alternatively this can be a string prefixed with php:representing a format that can be recognized by the PHP date()-function. @return string the formatted result. @throwsInvalidParamException if the input value can not be evaluated as a date value.@throwsInvalidConfigException if the date format is invalid. @seedatetimeFormat -
timestamp Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970). @param integer or string or DateTime $value the value to be formatted. The followingtypes of value are supported:1. an integer representing a UNIX timestamp; 2. a string that can be parsed to create a DateTime object. The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.; 3. a PHP DateTime object @return string the formatted result. -
relativetime Formats the value as the time interval between a date and now in human readable form.This method can be used in three different ways:1. Using a timestamp that is relative to now.2. Using a timestamp that is relative to the$referenceTime.3. Using aDateIntervalobject. @param integer or string or DateTime or DateInterval $value the value to be formatted. The following types of value are supported:1. an integer representing a UNIX timestamp; 2. a string that can beparsed to create a DateTime object.The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.; 3. a PHP DateTime object; 4. a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future) @param integer or string or DateTime $referenceTime if specified the value is used as a reference time instead ofnow when $value is not a DateIntervalobject. @return string the formatted result. @throwsInvalidParamException if the input value can not be evaluated as a date value.
intger Formats the value as an integer number by removing any decimal digits without rounding. @param mixed $value the value to be formatted. @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric.
decimal Formats the value as a decimal number.Property [[decimalSeparator]] will be used to represent the decimal point. The value is rounded automatically to the defined decimal digits. @param mixed $value the value to be formatted. @param integer $decimals the number of digits after the decimal point. If not given the number of digits is determined from the [[locale]] and if the PHP intl extension is not available defaults to 2. @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric.@seedecimalSeparator@seethousandSeparator
percent Formats the value as a percent number with "%" sign. @param mixed $value the value to be formatted. It must be a factor e.g. 0.75 will result in 75%. @param integer $decimals the number of digits after the decimal point.@param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].@param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric.
scientific Formats the value as a scientific number. @param mixed $value the value to be formatted. @param integer $decimals the number of digits after the decimal point. @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].@param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric.
currency Formats the value as a currency number.This function does not requires the PHP intl extension to be installed to work but it is highly recommended to install it to get good formatting results. @param mixed $value the value to be formatted. @param string $currency the 3-letter ISO 4217 currency code indicating the currency to use.If null, [[currencyCode]] will be used.@param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric. @throwsInvalidConfigException if no currency is given and [[currencyCode]] is not defined.
spellout Formats the value as a number spellout.This function requires thePHP intl extension to be installed. @param mixed $value the value to be formatted @return string the formatted result. @throwsInvalidParamException if the input value is not numeric. @throwsInvalidConfigException when the PHP intl extension is not available.
ordinal Formats the value as a ordinal value of a number. This function requires thePHP intl extension to be installed. @param mixed $value the value to be formatted @return string the formatted result. @throwsInvalidParamException if the input value is not numeric. @throwsInvalidConfigException when the PHP intl extension is not available.
shortsize Formats the value in bytes as a size in human readable form for example 12 KB.This is the short form of [[asSize]]. If [[sizeFormatBase]] is 1024, binary prefixes (e.g. kibibyte/KiB, mebibyte/MiB, ...) are used in the formatting result. @param integer $value value in bytes to be formatted. @param integer $decimals the number of digits after the decimal point. @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric. @seesizeFormat @seeasSize
size Formats the value in bytes as a size in human readable form, for example 12 kilobytes. If [[sizeFormatBase]] is 1024, binary prefixes (e.g. kibibyte/KiB, mebibyte/MiB, ...) are used in the formatting result. @param integer $value value in bytes to be formatted. @param integer $decimals the number of digits after the decimal point. @param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]]. @param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]]. @return string the formatted result. @throwsInvalidParamException if the input value is not numeric. @seesizeFormat @seeasShortSize

3. ActionColumn

ActionColumn是对一行数据进行操作的句柄。class指定处理的类,必须。 header指定表头显示,如果不写,默认为空。非必须。template中默认有三个:{view} {update} {delete},如果需要其他的,自行添加,比如下面添加了{onshelf} {offshelf}{robot}这三个。buttons除了默认的三个可以不写,其他都必须写。

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        [
            'class' => 'yii\grid\ActionColumn',
            'header' => '操作’,
            'template' => '{view} {update} {delete} {onshelf} {offshelf} {robot}',
            'buttons' => [
                'onshelf' => function ($url, $model, $key){
                    return    $model['status'] ? '' : Html::a('"glyphicon glyphicon-ok">',
                        ['item/shelf'],
                        ['title' => '上架商品', 'data' => ['method' => 'post', 'id' => $key, 'type' => 'on'], 'class'=> 'shelf']);
                },
                'offshelf' => function ($url, $model, $key){
                    return    $model['status'] ? Html::a('"glyphicon glyphicon-remove">',
                        ['item/shelf'],
                        ['title' => '下架商品', 'data' => ['method' => 'post', 'id' => $key, 'type' => 'off'], 'class'=> 'shelf']) : '';
                },
                
                'robot' => function ($url, $model, $key){
                    return     Html::a('"glyphicon glyphicon-knight">',
                        ['robot/like', 'id' => $model['pid'] ],
                        ['title' => '自动点赞', 'class' => 'post-autolike', 'data' => ['method' => 'post']]) ;
                },
            ]
        ],
    ],
]);
    

展示效果:

操作
查看 更新 删除 上架商品 下架商品 自动点赞

[gridview] -- 超详细使用_第1张图片把相应的文字替换成icon图标以及链接即可。


你可能感兴趣的:(Yii2)