According to the Yii2 documentation , I am supposed to be building the URL like following:
$appUrl = Yii::$app->urlManager->createUrl([Yii::$app->controller->id . '/' . Yii::$app->controller->action->id,'p1' => 'v1','p2' => 'v2'] , null);
It outputs:
/index.php?r=users%2Findex&p1=v1&p2=v2
Which is the correct output. Now, what if I have an array of params that I directly want to pass to the createUrl()
method? The following code explains my problem:
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$appUrl = Yii::$app->urlManager->createUrl([Yii::$app->controller->id . '/' . Yii::$app->controller->action->id,$arrayParams] , null);
The output in this case is:
/index.php?r=users/index&1[p1]=v1&1[p2]=v2
Whereas the output should have been:
index.php?r=users/index&p1=v1&p2=v2
Please note that $arrayParams
is generated by another method and I can't extract all the keys and values and pass them one by one in createUrl()
. That would be very costly IMO. How do I achieve this using Yii's api?
Use array_merge
to create required array structure.
$controller = Yii::$app->controller;
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$params = array_merge(["{$controller->id}/{$controller->action->id}"], $arrayParams);
Yii::$app->urlManager->createUrl($params);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With