0

I would like to define the format of an attribute in GridView based on a db field value. I was trying for example like this:

'format' => function ($model) {return $model->format;}, // it should return 'boolean'

but I have tried many other ways also, but it's not working. I'm getting:

PHP Notice – yii\base\ErrorException

Trying to get property of non-object

If I'm simply returning format as an attribute, it's working without any issues. It seems that it's not accepting it in the format section. Is it possible anyways what I'm trying to achieve? Can you please point me to the right direction?

2 Answers 2

1

Closures for format are not supported. You may use raw format and do formatting in Closure for value:

[
    'attribute' => 'name',
    'type' => 'raw',
    'value' => function ($model) {
        $format = 'as' . ucfirst($model->format);
        return Yii::$app->formatter->$format($model->name);
    },
],
Sign up to request clarification or add additional context in comments.

Comments

0

Refer Yii2 Formatter

Example:

<?= GridView::widget([
     'id' => 'grid-list',
     'dataProvider' => $dataProvider,
     [
         'attribute' => 'format_date',
          // 'format' => 'raw',
         'value' => function ($model) {
              // Here use \Yii::$app->formatter->asDate();
              // Ex: return \Yii::$app->formatter->asDate($model->format_date);
              return \Yii::$app->formatter->asDate($model->format_date);
         },
     ],
]) ?>

1 Comment

looks good: 'value' => function ($model) {return \Yii::$app->formatter->{$model->format}($model->value);}, Many thanks for both of you! It's a little bit hard to decide which one of you has earned the points, because rob006 has taken the time to fix my question, and he is explaining it better, however, technically your answer is also correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.