0

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

david
  • 39
  • 1
  • 14

1 Answers1

3

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.

Yupik
  • 4,932
  • 1
  • 12
  • 26
  • `'success-stories/'` - how about this? Maybe your slugs contains inappropriate characters. – Yupik Aug 11 '17 at 06:26
  • Great! `'success-stories/' => 'site/success-stories'` works. but my question is this . My slug value is like `this-value` maybe that's the reason `` is not working? – david Aug 11 '17 at 06:31
  • 2
    `this-value` contains `-` sign, by `\w+` you allow only "word characters" – Yupik Aug 11 '17 at 06:34
  • Thanks you're a great help :) – david Aug 11 '17 at 06:39