How to use Url::remember in yii2

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

I want to create a link on my error page to take user back to the previous link. Suppose the current URL is http://example.com/site/product, and a user try to view http://example.com/site/product?id=100 and a product with id =100 does not exit, the system should throw 404 error to the error page, now if i want to create a link to take the user back to http://example.com/site/product the previous URl how do I make this work. i can make this work by hardcoding this in my error views file, but i want it dynamically as i have many controller an action using the same view file.

I try this in my site conteoller

controller/site  public function actions() {      $url = Url::remember();     return [         'error' => [             'class' => 'yii\web\ErrorAction',         ],         $this->render('error',['url'=>$url]),      ]; } 

and try to get the value the in error view file like this

   /views/site/error.php    <p>     <?= Html::a('go back', [$url)?>  </p> 

but it has no vaule.. please any good idea on how to make this work, am also open to new solution

回答1:

this is form Yii2 Guide http://www.yiiframework.com/doc-2.0/guide-helper-url.html#remember-urls

There are cases when you need to remember URL and afterwards use it during processing of the one of sequential requests. It can be achieved in the following way:

// Remember current URL  Url::remember();  // Remember URL specified. See Url::to() for argument format. Url::remember(['product/view', 'id' => 42]);  // Remember URL specified with a name given Url::remember(['product/view', 'id' => 42], 'product'); 

In the next request we can get URL remembered in the following way:

$url = Url::previous();   // or  $productUrl = Url::previous('product'); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!