Yii2 - Pass variable from view to Gridview custom

2019-03-17 22:27发布

问题:

I want to save the last place that a user visited before he click onto "Edit" button in the gridview widget of a page. I created a variable named $lastAddress but I really dont know how to pass it onto the gridview and append it to the $url variable of "Edit" button. Can anyone show me how?

$lastAddress = 'xxx';
    <?=
        GridView::widget([
            ...
                [
                    'class' => 'yii\grid\ActionColumn',
                    'template' => '{view} {update} {delete}',
                    'buttons' => [
                        'update' => function ($url, $model) {
                            $url .= '&lastAddress=' . $lastAddress; //This is where I want to append the $lastAddress variable.
                            return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url);
                        },
                    ],
                ],
            ],
        ]);
        ?>

回答1:

Use use to pass in variables from the parent scope to a closure:

'update' => function ($url, $model) use ($lastAddress) {
    $url .= '&lastAddress=' . $lastAddress; //This is where I want to append the $lastAddress variable.
    return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url);
},


标签: gridview yii2