22

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);
                        },
                    ],
                ],
            ],
        ]);
        ?>
Lê Sỹ Hoàng
  • 409
  • 1
  • 3
  • 15

1 Answers1

67

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);
},
topher
  • 14,790
  • 7
  • 54
  • 70
  • my day too :-) Thanks – kasoft Jan 10 '17 at 12:49
  • I have another one doubt related to the above question. From the above when ever the update action is perform, they assign one static value to $lastAddress and combine the $lastAddress value with $url. But I have two column in dataProvider like wise, "tracker_id" and "id". I shown tracker_id as a link in gridview column. Whenever I click the tracker_id the corresponding dynamic id need to pass to the controlleraction. Can anyone help to me? Thanks in advance. – Nivetha Jaishankar Jun 15 '18 at 11:11
  • 1
    @topher Is it possible to do the other way around... set $lastAddress from within the function – Shahid Thaika Aug 09 '18 at 17:13
  • I need to do it the other way around too, once found a value, update variable with it...? – ShaunOReilly Nov 02 '19 at 02:33