1

I use the URL manager in Yii2 to create nice urls, which works, as long as there are no parameters on the url.

I set up the following config:

urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],

Using Url::to(array('crtl/action', 'paramx' => 'computer:net', 'paramy' => 'abc')) results in the following url:

http://localhost/crtl/action?paramx=computer:net&paramy=abc

But what I need is the following:

http://localhost/crtl/action/paramx/computer:net/paramy/abc

How can I prettify the url paramters to?

2 Answers 2

0

If your argument is number then rule of URL manager will be:

'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>'

If your argument is text then rule of URL manager will be:

'<controller:\w+>/<action:\w+>/<name:\w+>' => '<controller>/<action>'
Sign up to request clarification or add additional context in comments.

2 Comments

my arguments are sometimes numbers and sometimes text. so I have to add both?
Yes. You have to add both.
0

In case we declare pretty url, if we need result followed by '/' then we also need to define url rules for routing

    'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => [
                    '<controller:\w+>/<action:\w+>/<id:\w+>/<ids:\w+>' => '<controller>/<action>',
                ],
            ],

So we can call this routing as :

     <a href="<?php  echo \yii\helpers\Url::base(true)."/site/testing/5/8"?>">
     <a href="<?php echo \yii\helpers\Url::to(['site/testing','paramx'=>'x1','paramy'=>'y1'])?>">

In first case we had created the url as we want. In second case we had used url:to for routing as we can see we had provided paramX and param y in parameter.

For both of this,the result will be,

      public function actionTesting() {
        print_r(Yii::$app->request->getQueryParams());
        die();
  
    }//will get the query params that we had sent

    Output will be:Array ( [paramx] => x1 [paramy] => y1 ) ;

As the case you are asking is not the url routing pattern for yii2,this is the preferred way for yii2

1 Comment

shouldn't Url::to create an "nice" URL, like .../paramx/x1/paramy/y1? Using your rule has no effect, of the output of Url::to. It still generates the &parmx=x1&paramy=y1 version.

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.