david
david

Reputation: 39

YII 2 Url Route not working with $_GET parameters

I'm new to Yii2 and their URL ruling is kinda tricky. I have a SiteController with an action like this

public function actionSuccessStories($slug = null)
{
    // some codes
}

in my config i have this

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'enableStrictParsing' => true,
    'rules' => [
        // Default routes
        '<controller:\w+>/<id:\d+>' => '<controller>/view',
        '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',

        // page routes
        'success-stories/<slug:\w+>' => 'site/success-stories',

        // Remove 'site' parameter from URL
        '<action:(.*)>' => 'site/<action>',
    ],
],

in my view i have this to generate my url

Url::to(['site/success-stories', 'slug' => 'slug_value'], true);

my problem is Url::to(); creates success-stories?slug=slug_value

instead of

success-stories/slug/slug_value am i doing this right? What i want to accomplish is the second format.

I've read this question related to mine but it covers only modules Yii2 url manager don't parse urls with get parameter

Upvotes: 0

Views: 1884

Answers (1)

Yupik
Yupik

Reputation: 5032

Change your rules to:

'rules' => [
    // page routes
    'success-stories/<slug:\w+>' => 'site/success-stories',

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

    // Remove 'site' parameter from URL
    '<action:(.*)>' => 'site/<action>',
],

Order of rules is important, Yii2 will try to match rule one by one, if it fits - it will use it.

Upvotes: 3

Related Questions