Search code examples
phpgridviewyii2

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


Solution

  • 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();