Yii2 GridView的使用方法

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

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'   // 用户名
    ]
]);

展示结果:

OrderNoUsername
123345698763Test用户
236479547829Joyven

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

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

展示结果:

日期PVUV
2016年9月10日85006384
2016年9月9日83786523

用法三:数据过滤,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说明参数返回备注
rawFormats the value as is without any formatting. This method simply returns back the parameter without any format.The only exception is a null value which will be formatted using [[nullDisplay]].@param mixed $value the value to be formatted. @return string the formatted result.-
textFormats the value as an HTML-encoded plain text.@param string $value the value to be formatted. @return string the formatted result.-
ntextFormats 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.-
htmlFormats 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.-
dateFormats 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 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. @throws InvalidParamException if the input value can not be evaluated as a date value. @throws InvalidConfigException if the date format is invalid.
timeFormats 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 DateTime object @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. @throws InvalidParamException if the input value can not be evaluated as a date value. @throws InvalidConfigException if the date format is invalid.@see timeFormat
paragraphsFormats the value as HTML-encoded text paragraphs.Each text paragraph is enclosed within a <p> tag.One or multiple consecutive empty lines divide two paragraphs.@param string $value the value to be formatted. @return string the formatted result.-
emailFormats 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.-
imageFormats 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.-
urlFormats 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.-
booleanFormats the value as a boolean.@param mixed $value the value to be formatted. @return string the formatted result. @see booleanFormat-
datetimeFormats 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. @throws InvalidParamException if the input value can not be evaluated as a date value.@throws InvalidConfigException if the date format is invalid. @see datetimeFormat-
timestampFormats 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.-
relativetimeFormats 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 a DateInterval object.@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 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; 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 of now when $value is not a DateInterval object. @return string the formatted result. @throws InvalidParamException if the input value can not be evaluated as a date value.
intgerFormats 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. @throws InvalidParamException if the input value is not numeric.
decimalFormats 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. @throws InvalidParamException if the input value is not numeric.@see decimalSeparator @see thousandSeparator
percentFormats 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. @throws InvalidParamException if the input value is not numeric.
scientificFormats 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. @throws InvalidParamException if the input value is not numeric.
currencyFormats 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. @throws InvalidParamException if the input value is not numeric. @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined.
spelloutFormats the value as a number spellout.This function requires the PHP intl extension to be installed.@param mixed $value the value to be formatted @return string the formatted result. @throws InvalidParamException if the input value is not numeric. @throws InvalidConfigException when the PHP intl extension is not available.
ordinalFormats the value as a ordinal value of a number. This function requires the PHP intl extension to be installed.@param mixed $value the value to be formatted @return string the formatted result. @throws InvalidParamException if the input value is not numeric. @throws InvalidConfigException when the PHP intl extension is not available.
shortsizeFormats 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. @throws InvalidParamException if the input value is not numeric. @see sizeFormat @see asSize
sizeFormats 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. @throws InvalidParamException if the input value is not numeric. @see sizeFormat @see asShortSize

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('<span class="glyphicon glyphicon-ok"></span>',
                        ['item/shelf'],
                        ['title' => '上架商品', 'data' => ['method' => 'post', 'id' => $key, 'type' => 'on'], 'class'=> 'shelf']);
                },
                'offshelf' => function ($url, $model, $key){
                    return    $model['status'] ? Html::a('<span class="glyphicon glyphicon-remove"></span>',
                        ['item/shelf'],
                        ['title' => '下架商品', 'data' => ['method' => 'post', 'id' => $key, 'type' => 'off'], 'class'=> 'shelf']) : '';
                },
                
                'robot' => function ($url, $model, $key){
                    return     Html::a('<span class="glyphicon glyphicon-knight"></span>',
                        ['robot/like', 'id' => $model['pid'] ],
                        ['title' => '自动点赞', 'class' => 'post-autolike', 'data' => ['method' => 'post']]) ;
                },
            ]
        ],
    ],
]);
    

展示效果:

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

图片描述
把相应的文字替换成icon图标以及链接即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值