Alexander Kolovsky
Alexander Kolovsky

Reputation: 105

Why can't I change the value in GridView?

Trying to replace the input value with the users table column status to blocked, if it is equal to 0 and active, if is 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'],
    ],
]);

But displays an error: array_merge(): Argument #2 is not an array What am I doing wrong, please tell me

Upvotes: 2

Views: 3789

Answers (2)

arogachev
arogachev

Reputation: 33548

Attribute status should be declared like this:

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

So the whole GridView will look like this:

<?= 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'],
    ],
]) ?>

But another way of doing this is recommended.

Place in your model:

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];
}

And now you can replace your closure content to this:

return $model->getStatusLabel();

Upvotes: 5

Chinmay Waghmare
Chinmay Waghmare

Reputation: 5456

Try:

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'],
    ],
]);

Upvotes: 0

Related Questions