2018-06-11 12:45
浏览 122

Yii2 GridView属性格式由不同的属性值定义

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?

图片转代码服务由CSDN问答提供 功能建议

我想基于db字段在 GridView 中定义属性的格式 值。 我试图这样的例子:

 'format'=>  function($ model){return $ model-> format;},//它应该返回'boolean'

但我也尝试了很多其他方法, 但它不起作用。 我得到了:

PHP注意 - yii \ base \ ErrorException


如果我只是将 format 作为属性返回,它的工作没有任何问题。 它似乎不是在格式部分接受它。 无论如何我可能实现的是什么? 你能指点我正确的方向吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyang0005
    dongyang0005 2018-06-11 13:02

    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);
    点赞 评论
  • doupike2351
    doupike2351 2018-06-11 13:02

    Refer Yii2 Formatter


    <?= 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);
    ]) ?>
    点赞 评论