skip to Main Content

For SEO purposes I need to remove the first page number from the URL. i.e I have the following:

example.com/pages/view/1 and example.com/pages/view the two URLs points to the same contents of the view action. I want to make the pagination free from 1 in the URL. i.e first Page link and Page Number 1 should be linked to pages/view.

I tried to deal with the $pagination object like the following:

$pages = new Pagination(['totalCount' => $books['booksCount'], 'pageParam' => 'start', 'defaultPageSize' => 10,]);
      $pagingLinks = $pages->getLinks();
      $pagingLinks['first'] = '/';
      $pages->links = $pagingLinks;

However, the last line causing error:

Setting read-only property: yiidataPagination::links

So I have a problem to modify the links property. Is there any other solution to get this task done?!

2

Answers


  1. Chosen as BEST ANSWER

    The above answer may works for direct use of Pagination but remain an issue if it was used from another widget such as ListView.

    I found the solution from a comment on an issue report on Yii2 repository on github

    The solution is just define proper route in config/web.php. Suppose here we have a controller called Suras and we use the ListView widget on its action's view called view. So placing rule array with defaults has value 'page' => 1 will prevent adding the page parameter to the link's URL of the first page. Also notice the first rule 'view/<id:d+>/1' => 'Error404', is placed in-order to prevent any access to the first page using page=1 parameter, for example, trying to access mysite.com/view/20/1 will invoke 404 error, because there is no controller called Error404.

    'urlManager' => [
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                'rules' => [                
                    'view/<id:d+>/1' => 'Error404',
                    ['pattern' => 'view/<id:d+>/<page:d+>', 'route' => 'suras/view', 'defaults' => ['page' => 1]],
                    'view/<id:d+>/<page:d+>' => 'suras/view',
                    'view/<id:d+>' => 'suras/view',
                ],
            ],
    
    
    ],
    

  2. According to docs you should set yiidataPagination::forcePageParam to false by passing it in Pagination constructor

    $pages = new Pagination([
        'totalCount' => $books['booksCount'], 
        'pageParam' => 'start', 
        'defaultPageSize' => 10,
        'forcePageParam' => false,
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search