4

I need to add some parameter to url by using render in a Yii2 controller action. For example add cat=all parameter to following url:

localhost/sell/frontend/web/index.php?r=product/index

and this is my index action :

return $this->render('index', [
    'product' => $product,    
]);

3 Answers 3

4

You can create URL like below:

yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']);

You can redirect in controller like below:

$this->redirect(yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']));

Then render your view.

Sign up to request clarification or add additional context in comments.

2 Comments

how should i use toRoute or redirect within this->render? im gonna to have GET parameter in addition to Post parameter in a renderd view url
This answer is inaccurate, toRoute will render: /product/index?1%5Bcat%5D=all in the examples provided here because it does not permit sub-arrays, see docs
1

To generate url using the Yii2 yii\helpers\Url to() or toRoute() method:

$url = yii\helpers\Url::to(['product/index', 'cat' => 'all']);

or:

$url = yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']);

And you can then redirect in controller:

return $this->redirect($url);

Also note that the controller redirect() method is merely a shortcut to yii\web\Response::redirect(), which in turn passes it's first argument to: yii\helpers\Url::to(), so you can feed your route array in directly like so:

return $this->redirect(['product/index', 'cat' => 'all']);

Please Note: the other answer by @ali-masudianpour may have been correct in earliest versions of Yii2, but in later versions of Yii2 (including latest - 2.0.15 at time of writing), the Url helper methods only accept unidimensional arrays, which are in turn passed into yii\web\UrlManager methods like createUrl.

Comments

0

You can make redirect route into your controller like this:

$this->redirect(yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']));

1 Comment

While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.