dqkf49487 2016-10-23 19:29
浏览 54
已采纳

如何知道yii2 Gridview上的列名[重复]

This question already has an answer here:

On my system the user can create the column with the name they want, so I save the column name into database

I am using this code on column options:

foreach((new Field)->listFields as $item){

  data = [
    'attribute' => $item->name,
    'value' => function($model){
        return $model->$item->name; // the problem is here, $item->name is out of the scope
     },
  ];
  array_push($columns, $data);
}

return $this->render('index', [
  'model' => $model,
  'dataProvider' => $dataProvider,
  'columns' => $columns,
]);

this is my index view:

<?= \yii\grid\GridView::widget([
   'dataProvider' => $dataProvider,
   'formatter' => ['class' => 'yii\i18n\Formatter'],
   'columns' => $columns,
]); ?>

I want to use the value, because I would like to format the data if the $item->type is X or Y. ex:

'value' => function($model){
    if($item->type == 'img'){
       return Html::img($model->$item->name),
    else {
        return $model->$item->name;
    }
 },

the return of the listField is just an array:

Array
(
    [0] => stdClass Object
        (
            [name] => ITEM_1
            [type] => txt
        )

    [1] => stdClass Object
        (
            [name] => IMAGE_1
            [id] => img
        )

    [2] => stdClass Object
        (
            [name] => IMAGE_2
            [id] => img
        )
)

and the return of the sql in dataProvider is

Array
(
    [0] => Array
        (
            [ITEM_1] => Item 1 blablabla
            [IMAGE_1] => http://url.jpg
            [IMAGE_2] => http://url2.jpg
            [id] => 1
        )

)

As I am using dynamic column, I can't hardcode the column name like $mode->IMAGE_1

</div>
  • 写回答

2条回答 默认 最新

  • drtzb06222 2016-10-23 21:57
    关注

    As you said, $item is out of scope, and as said in php doc about anonymous functions (not specific to yii) :

    Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.

    You should simply add use ($item) :

    'value' => function($model) use ($item) {
        return $model->{$item->name};
     },
    

    PS: this question should be closed since it is a duplicate

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了