user2337304
user2337304

Reputation: 23

Yii routes and creation of URLs with multiple parameters

I would like to get the URL as follow:

http://domain.com/post/1/some-titles-here

But I'm getting:

http://domain.com/post/1?title=some-titles-here

I am using this config:

'urlFormat' => 'path',
...
//'post/<id:\d+>/<title>' => 'post/view/', 
'post/<id:\d+>/<title:\w+>' => 'post/view/',
'post/<id:\d+>' => 'post/view/',
...

Then to get the URL I am executing:

Yii::app()->createAbsoluteUrl('post/view', array('id' => $this->id,'title' => $this->title));

im following the third rule here: http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-named-parameters

Upvotes: 0

Views: 4915

Answers (2)

Andrew G Chvyl
Andrew G Chvyl

Reputation: 41

This is a code that work for me:

'urlManager'=>array(
    'urlFormat'=>'path',
    'showScriptName' => false,
    'rules'=>array(
         '' => 'site/index',
         'article/<id:\d+>/<alias:[-\w]+>' => 'article/view',
         'article/cat/<id:\d+>-<alias:[-\w]+>' => 'category/view',

Result urls:

Upvotes: 0

frostyterrier
frostyterrier

Reputation: 1912

The regular expression you're using to match the title is incorrect: <title:\w+> will only match single words but your title has hyphens as well.

Tuan is correct; it's matching the next rule. That's because the URL manager works its way down the rules until it finds one that matches.

Use this rule instead:

'post/<id:\d+>/<title:([A-Za-z0-9-]+)>' => 'post/view/',

That will match titles with letters, numbers, and hyphens.

Upvotes: 1

Related Questions