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?

5
  • So you want example.com/page/1 route to be accessed via url example.com, then later pages via example.com/page/2, example.com/page/3 etc? Commented Jun 27, 2018 at 10:51
  • Yes, that's right. Commented Jun 27, 2018 at 11:05
  • OK, in your main config do you have a default route configured as: 'defaultRoute' => 'site/index' ? Commented Jun 27, 2018 at 11:22
  • example.com now open site/index, my problem is when in example.com/page/2 click on previous page in pagination, instead example.com opened example.com/page Commented Jun 27, 2018 at 11:32
  • OK, I have an answer Commented Jun 27, 2018 at 11:39

1 Answer 1

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',
    ],
],
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent, glad to help!
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]).
True, I don't like to use action defaults, hence why the better option listed first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.