Search code examples
gridviewyii2yii2-advanced-appyii2-model

Yii2 GridView comparing Column content data to other controller rendered param


I've created a Yii2 Gridview widget and i'd like to display "V" mark only on row equals another renderred variable i pass from controller:

        <?=
             GridView::widget([
                               'dataProvider' => $dataProvider,
                               'filterModel' => $searchModel,
                                'columns' => [
                                        [
                                            'header' => 'Default',
                                            'content' => function ($model) {
                                              if ($model->id == $selected) {
                                                return Html::tag('i','',['class' => 'fa fa-check']);
                                              }
                                              return '';
                                            }
                                        ],

passing from controller:

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

But i receive an error:

Undefined variable: selected

What did i miss?


Solution

  • The variable $selected does not exist within the scope of the anonymous function. From the php.net page for anonymous functions:

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

    i.e:

    'content' => function ($model) use ($selected) { ...