Yii2 GridView是實現yii網格視圖的小部件,通常用於報表視圖的展現。今天,結合DataProvider(ArrayDataProvider
以及SqlDataProvider
)說一下GridView中的幾個Columns(SerialColumn
,DataColumn
,ActionColumn
)。php
SerialColumn就是連續的列,主要用於網格的行號,屬於自增式的列。用法很簡單:html
echo GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], // 連續編號 // 其餘數據列和操做列 ] ]);
展現結果:git
# |
1 |
2 |
DataColumn主要展現數據的,全部跟數據有關的展現基本都在這個Column中實現。所以用法也不少,可是有一條,若是對數據不作處理,那麼字段必須是ArrayDataProvider
對象的allModels
的二維數組的key或者是SqlDataProvider
對象sql查詢結果二維數組的key。sql
用法一:表頭即字段名,首字母大寫數組
echo GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'orderNo', //訂單編號 'username' // 用戶名 ] ]);
展現結果:less
OrderNo | Username |
123345698763 | Test用戶 |
236479547829 | Joyven |
用法二:定義表頭並格式化數據yii
echo GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'time:date:日期', 'pv:raw:PV', 'uv:raw:UV', ] ]);
展現結果:ide
日期 | PV | UV |
2016年9月10日 | 8500 | 6384 |
2016年9月9日 | 8378 | 6523 |
用法三:數據過濾,class
、attribute
、label
、format
均不是必需要的。class
默認是yii\grid\DataColumn
,attribute
是指定排序的字段key,必定是dataProvider中提供的數據的key,若是不指定,對於過濾的數據,不能點擊表頭排序。post
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支持的格式:ui
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 null value 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 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. | |
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 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 | |
paragraphs | Formats 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. | - | |
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. | @see booleanFormat | - | |
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. | @throws InvalidParamException if the input value can not be evaluated as a date value.@throws InvalidConfigException if the date format is invalid. @see datetimeFormat | - |
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 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. | |
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. | @throws InvalidParamException 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. | @throws InvalidParamException if the input value is not numeric.@see decimalSeparator @see thousandSeparator | |
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. | @throws InvalidParamException 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. | @throws InvalidParamException 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. | @throws InvalidParamException if the input value is not numeric. @throws InvalidConfigException if no currency is given and [[currencyCode]] is not defined. | |
spellout | Formats 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. | |
ordinal | Formats 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. | |
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. | @throws InvalidParamException if the input value is not numeric. @see sizeFormat @see asSize | |
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. | @throws InvalidParamException if the input value is not numeric. @see sizeFormat @see asShortSize |
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圖標以及連接便可。