Reputation: 7895
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,
]);
Upvotes: 4
Views: 10566
Reputation: 63
You can make redirect route into your controller like this:
$this->redirect(yii\helpers\Url::toRoute(['product/index', 'cat' => 'all']));
Upvotes: 0
Reputation: 14459
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.
Upvotes: 4
Reputation: 1492
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.
Upvotes: 1