52

Now My application is using gridview to list all information and it's also have pagination.when the user click on pagination number and then click on edit and then save. It redirect user to view page. What I want to do it to redirect user to previous page(url with pagination number).

arogachev
  • 33,150
  • 7
  • 114
  • 117
Chhorn Soro
  • 3,061
  • 8
  • 27
  • 43

4 Answers4

142

You could use Yii::$app->request->referrer which returns the last page the user was on.

Usage is straightforward:

return $this->redirect(Yii::$app->request->referrer);

You need also take into account that referrer can be null:

return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);

See the docs.

deacs
  • 4,259
  • 2
  • 27
  • 37
  • 2
    Second example can be shortened to `return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);` – cronfy Sep 20 '17 at 16:57
  • but referrer URL is not got when we reached from one URL which is not accessed by the guest. I think it can get by return URL but how can I manage the referral url and return url. – Bhavin Thummar May 29 '19 at 07:17
12

Here it says that it's a good practice to check if referrer is set at the first place. So if you use the following code you will be redirected to last page if referrer is set or to your configured homeUrl if the return URL was not set previously.

return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));

goBack() details

redirect details

Kostas Mitsarakis
  • 4,772
  • 3
  • 23
  • 37
2

It is true what @Kostas says, but I think it would be better if you simply code the following, because goBack take account of a null parameter already to goBack HOME.

return $this->goBack(Yii::$app->request->referrer);

I tested it and it works fine.

daniroyo
  • 47
  • 5
0

If you use Html::submitButton when you are in a form and you want to be redirected to the previous page, so mostly to your module list I recommend using use yii\helpers\Url;:

return $this->redirect(Url::previous('previous') ?: ['list']);

because

return $this->redirect(Yii::$app->request->referrer);

will return you back to the form instead of a module list.

Paweł Nowicki
  • 49
  • 1
  • 10