Reputation: 435
How can i redirect user to previous page after updating a record? this is the typical scenario:
Ive tried using below in my controller after updating
return $this->redirect('index',302); (this is not what I need)
return $this->redirect(Yii::$app->request->referrer); (this gets user back to update view and not to index view with filters)
return $this->goBack(); (this gets user to homepage)
Thanks!
Upvotes: 5
Views: 3879
Reputation: 9728
I would suggest the following in a typical update action method:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if(Yii::$app->request->isGet) {
Url::remember($this->request->referrer, $this->action->uniqueId);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(
Url::previous($this->action->uniqueId) ?: ['view', 'id' => $model->id]
);
}
return $this->render('update', [
'model' => $model,
]);
}
The URL will be remembered only if it is a GET request (typical first call), because the action could be called again if validation fails. Then it is a POST call and you don't want to remember the referrer that is now the update action itself.
When saving succeeded then you can redirect to the remembered URL. If for some reason there is no URL remembered, the standard (or whatever) will be used.
I've added a name to URL::remember() and Url::previous(). It should be unique and only gets used in this action. This is the case for $this->action->uniqueId. I think this should be done, since the user could have more than one tab open, navigating somewhere else in the app and you might have more update actions with the same mechanism. If a unique name is not supplied, then the last remembered URL gets used and that could be a different, unexpected one. User would get confused then.
Compared to the approach of Bizley this solution is self-contained in the action itself. No need to remember the previous URL in other actions.
Update: The solution still has a problem, but it is accetable. Take a look here for more.
Upvotes: 2
Reputation: 18021
In the action you want user to be redirected to add
\yii\helpers\Url::remember();
Now next call in any controller like:
return $this->goBack();
Will redirect user to the "marked" action.
Upvotes: 8