Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - createUrl() with array of params?

Tags:

php

yii2

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?

like image 447
Gogol Avatar asked Jul 15 '15 07:07

Gogol


Video Answer


1 Answers

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);
like image 172
Justinas Avatar answered Sep 26 '22 17:09

Justinas