Search code examples
phpyii2yii2-advanced-app

yii2 back to previous page after update


How can i redirect user to previous page after updating a record? this is the typical scenario:

  • Users is in index page and filters results or paginates over the records, then they find the one that they want to edit and click the edit button. They update that record's data and once they click on "update" button they whould be redirected to index view but with the filters/page previously selected.

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!


Solution

  • 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.