一: 显示状态名称
在cms新闻管理中,通常会有推荐/最新等状态,通常储存是以数字形式存储,所以需要根据数字获取状态名称
在yii中可以这样实现:
首先在News的ActiveRecord中定义函数:
public function getStatus($status){
$status_arr = [
'0' => yii::t('common', 'not show'),
'1' => yii::t('common', 'show'),
'2' => yii::t('common', 'recommend'),
];
if(array_key_exists($status, $status_arr)){
return $status_arr[$status];
}else{
return yii::t('common', 'not set');
}
}
在gridview中有这几个定义:
public $attribute;
public $value; The signature of this function should be: `function ($model, $key, $index, $column)`. Where `$model`, `$key`, and `$index` refer to the model, key and index of the row currently being rendered and `$column` is a reference to the [[DataColumn]] object.
public $format = 'text'; (e.g. `"raw"`, `"text"`, `"html"`, `['date', 'php:Y-m-d']`).
那么我们可以这样显示状态名称:
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
'describe:ntext',
'status' => [
'attribute' => 'status',
'value' => function ($model) {
return $model->getStatus($model->status);
},
],
['class' => 'yii\grid\ActionColumn'],
],
二: 日期格式化
cms的日期通常是储存时间戳,所以显示时需要格式化
同样对于日期格式化可以这样使用:
[
'attribute' => 'create_time',
'format' => ['date', 'php:Y-m-d'],
],