The Bndr
The Bndr

Reputation: 13394

Yii2 does not create nice url - parameter

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?

Upvotes: 1

Views: 669

Answers (2)

Mohan
Mohan

Reputation: 616

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

Upvotes: 0

Prakash Pazhanisamy
Prakash Pazhanisamy

Reputation: 983

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>'

Upvotes: 0

Related Questions