为什么我不能在GridView中更改值?

时间:2015-05-16 13:24:52

标签: gridview yii2

尝试将用户表列状态替换为阻止的输入值,如果它等于0且处于活动状态,则为10。

 GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'username',
        'email:email',
        'status',
            'value' => function ($model){
                    return $model->status==10 ? "Active":"Blocked";
                },


        ['class' => 'yii\grid\ActionColumn'],
    ],
]);

但显示错误: array_merge():参数#2不是数组 我做错了什么,请告诉我

2 个答案:

答案 0 :(得分:5)

属性status应该像这样声明:

[
    'attribute' => 'status',
    'value' => function ($model) {
         return $model->status == 10 ? 'Active' : 'Blocked';
    },
],

所以整个GridView看起来像这样:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'username',
        'email:email',
        [        
            'attribute' => 'status',
            'value' => function ($model) {
                return $model->status == 10 ? 'Active' : 'Blocked';
            },
        ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
]) ?>

但建议采用另一种方法。

放入你的模特:

const STATUS_BLOCKED = 0;

const STATUS_ACTIVE = 10;

/**
 * @return array
 */
public static function getStatusesList()
{
    return [
        self::STATUS_BLOCKED => 'Blocked',
        self::STATUS_ACTIVE => 'Active',
    ];
}

/**
 * @return string
 */
public function getStatusLabel()
{
    return static::getStatusesList()[$this->status];
}

现在您可以将关闭内容替换为:

return $model->getStatusLabel();

答案 1 :(得分:0)

尝试:

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'username',
        'email:email',
        [
            'label' =>'status',
            'value' => function($data) {
                 return $data->status==10 ? "Активен":"Заблокирован";
            },
        ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
]);