9

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?

4
  • For only one parameter: <?= Yii::$app->urlManager->createUrl(["post/view","id"=>$post->id]) ?> Commented Apr 25, 2016 at 10:13
  • It's good to use Url::to() instead of Yii::$app->urlManager->createUrl() Commented Dec 11, 2017 at 16:05
  • @GermanKhokhlov I agree. I was relatively new to Yii 2 when I asked this. I had no idea that we have Url::to() method available back then. It's short and not linked to the $app, which I like. Commented Dec 12, 2017 at 8:32
  • 1
    @Gogol It's for other people who will find it. Cause I was looking for this shortcut when coming here. Commented Dec 15, 2017 at 12:47

2 Answers 2

18

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet thank you. Exactly what I was looking for. Marking your answer as accepted :)
0

Same result you can achieve using Yii::$app->controller->route

$route = Yii::$app->controller->route;
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$params = array_merge([$route], $arrayParams);
Yii::$app->urlManager->createUrl($params);

Comments

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.