Beautifying URLs thru urlManager rules works one way only

100 views Asked by At

I followed this tut (copy of this) for creating custom rule for named parameters. In my rules array i've added 2 upper lines to parse backwards and forwards Assortment[groupCategory] parameter.

  'urlManager'=>array( 
        'showScriptName'=>false, 
        'urlFormat'=>'path',
        'rules'=>array(      
             'assortment/<Assortment[groupCategory]:\d+>'=> 'assortment/index',
             'assortment/<Assortment%5BgroupCategory%5D:\d+>'=> 'assortment/index', 
             '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
             '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', 
         ),
       ),

This works forward: with http://tarex.ru/assortment/index/Assortment[groupCategory]/1 the yii recognize Assortment[groupCategory] as a GET parameter equal 1.

But if from a form i request

  • http://tarex.ru/assortment/index?Assortment[groupCategory]=2 or
  • http://tarex.ru/assortment/index?Assortment%5BgroupCategory%5D=2

it does not transform it into the human readable ulr, like this:

http://tarex.ru/assortment/index/Assortment[groupCategory]/2

Why? The tut sais it's two-way url manager.

On the other hand, when creating a URL with the route post/index and parameter tag, the urlManager component will also use this rule to generate the desired URL /index.php/posts/yii. For this reason, we say that urlManager is a two-way URL manager.

1

There are 1 answers

6
Maug Lee On BEST ANSWER

it does not transform it into the human readable ulr

Yes, Yii does not transform url in browsers address bar, nor in forms action parameter. Everything is run „behind scenes“.

I recommend you to rewrite your rule

'assortment/<Assortment[groupCategory]:\d+>'=> 'assortment/index'

to

'assortment/<groupCategory:\d+>'=> 'assortment/index'

In this way, if you go to url http://tarex.ru/assortment/index/1 an actionIndex() method will be called in controller named AssortmentController. And parameter $groupCategory = 1 will be passed to it. To handle passed variable you probably need to change methods signature to:

public function actionIndex( $groupCategory ) {}

The „back-way“ will be if you create url by getting parameters in this way:

echo Yii::app()->controller->createUrl( 'assortment/index', array( 'groupCategory' => 1 ) ) ;

a url /assortment/index/1 must be created.