Format dynamic column value on Gridview

Hi

I have a similar problem to this:

http://www.yiiframework.com/forum/index.php/topic/56128-formatting-dynamic-columns/page__p__255609__hl__Dynamic+Column+#entry255609

But I am using Yii2

I would like to know how to get the column name inside the ‘value’ => function($model)

follow my code:

Controller:




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,

]);



Follow my 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] => link to image 1

            [IMAGE_2] => link to image 2

            [id] => 1

        )


)



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

Hi

I did ask the same question on stack overflow and I got the answers

We have to use ‘use’





'value' > function($mode) use ($item) {

  

     return $model->$item->name;


}