Yii2 Url rules with multiple parameters

1.7k views Asked by At

I have problem to set url rules with multiple parameters. I have the action "description" in controller "Article" like this:

public function actionDescription($aID, $aTitle){ ... }

Then i set the url rules like this:

 'Article/description/<aID:\d+>/<aTitle:\S+>' => 'article/description',

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

When i call a url through a link like this:

<?= Html::a( Html::encode($model->aTeaser), 
            ['article/description', 'aID' => $model->aID, 'aTitle' => $model->aTeaser], 
            ['class'=>'link_article'])
                ?>

I still get this url:

http://test.com/article/description?aID=323&aTitle=teaser+of+this+article

instead of this:

http://test.com/article/description/323/teaser+of+this+article
2

There are 2 answers

1
topher On BEST ANSWER

You don't have to specify the escape sequence for the last parameter if you are sure you won't have any parameter after it:

'article/description/<aID:\d+>/<aTitle>' => 'article/description'
4
Bizley On

It's because you parse the route twice. Html::a() is calling Url::to() on the URL so there is no need to do it yourself. And what's the deal with empty strings everywhere? It should be:

<?= Html::a(
    Html::encode($model->aTeaser), 
    ['article/description', 'aID' => $model->aID, 'aTitle' => $model->aTeaser], 
    ['class' => 'link_article']
) ?>

PS. What's the point of second rule with <aTitle:\s+> where you try to match all whitespace characters?