2

My index rules like as below:

[
    'pattern' => 'page/<page:\d+>',
    'route' => 'site/index',
],

it work, but in pagination, firest page is example/page/1, i change rules as below:

[
    'pattern' => 'page/<page:\d+>',
    'route' => 'site/index',
    'defaults' => ['page' => 1],
],

Now first page has become to example.com/page.

How write rules, to first page in pagination show like example.com?

ajmedway
  • 1,492
  • 14
  • 28
Masoud92m
  • 602
  • 1
  • 8
  • 24

1 Answers1

1

As per your question in conjunction with your comments, I suggest that you additionally add a rule for a blank url pattern, i.e. for url with domain only, that is directed to your defaultRoute with a default $page parameter value.

'rules' => [
    [
        'pattern' => '',
        'route' => 'site/index',
        'defaults' => ['page' => 1],
    ],
    [
        'pattern' => 'page/<page:\d+>',
        'route' => 'site/index',
    ],
],

Then, in your controller action you can test this url rule is working as follows:

public function actionIndex($page)
{
    echo '<pre>';
    echo 'site / index / $page ' . print_r($page, true);
    echo '</pre>';
    exit;
}

Also note that you could set the default in the method declaration of your controller action like so:

public function actionIndex($page = 1)
{
    echo '<pre>';
    echo 'site / index / $page ' . print_r($page, true);
    echo '</pre>';
    exit;
}

Which would allow you to simplify your config as follows:

'rules' => [
    [
        'pattern' => '',
        'route' => 'site/index',
    ],
    [
        'pattern' => 'page/<page:\d+>',
        'route' => 'site/index',
    ],
],
ajmedway
  • 1,492
  • 14
  • 28
  • Excellent, glad to help! – ajmedway Jun 27 '18 at 13:48
  • Configuring default values for route params as a parameters in action method is tricky and can be considered as a code smell. It will not work as expected if you will try create URL by `Url::to(['site/index', 'page' => 1])`. – rob006 Jun 27 '18 at 15:24
  • True, I don't like to use action defaults, hence why the better option listed first – ajmedway Jun 27 '18 at 16:31