dongmaoxi0477 2018-06-11 12:45
浏览 127
已采纳

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?

  • 写回答

2条回答 默认 最新

  • 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 2018-06-11 13:02
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 Matlab计算100000*100000的矩阵运算问题:
  • ¥50 VB6.0如何识别粘连的不规则的数字图片验证码
  • ¥16 需要完整的这份订单所有的代码,可以加钱
  • ¥30 写一个带界面控制的机房电脑一键开机关机并且实时监控的软件
  • ¥15 Stata数据分析请教
  • ¥15 请教如何为VS2022搭建 Debug|win32的openCV环境?
  • ¥15 关于#c++#的问题:c++如何使用websocketpp实现websocket接口调用,求示例代码和相关资料
  • ¥15 51单片机的外部中断,按下按键后不能切换到另一个模式
  • ¥15 java连接sqlserver有问题
  • ¥15 yolov8 如何调cfg参数