user2511599
user2511599

Reputation: 852

Yii2 GridView attribute format defined by different attribute value

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?

Upvotes: 0

Views: 846

Answers (2)

vishuB
vishuB

Reputation: 4261

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

Upvotes: 0

rob006
rob006

Reputation: 22154

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

Upvotes: 1

Related Questions