Thursday, September 12, 2013

Inserting named parameter for custom pagination route

I'm using the pagination component and would like to use a custom route for a prettier URL. At the moment I have a page at /things, and I would like the individual pages to be /things/2, /things/3 etc. I'm using the following code in my thing controller's action:

public function index() {
    $this->set('things', $this->paginate());
}

Then, in my element (which is included into the view for the index action) I've got the pagination helper showing number links:

echo $this->Paginator->numbers(array(
    'separator' => '',
    'tag' => 'li',
    'currentTag' => 'a',
    'currentClass' => 'active'
));

As that stands, it works perfectly. I can use the page numbers and get the correct page. I then tried to add this route to make some pretty page URLs:

Router::connect('/things/:page', array('controller' => 'things', 'action' => 'index'), array('page' => '[0-9]+'));

Now, the pagination helper correctly outputs the pretty URLs, however when I click them the page doesn't change even though the URL does. So I end up on /things/3 and I'm seeing results for the first page. After a bit of digging, I think this is because the named parameter "page" isn't being sent as a named parameter. Below is a dump of $this->request->params:

array(
    'plugin' => null,
    'controller' => 'things',
    'action' => 'index',
    'named' => array(),
    'pass' => array(),
    'page' => '2'
)

So, I amended my route like so:

Router::connect('/things/:page', array('controller' => 'things', 'action' => 'index'), array('page' => '[0-9]+', 'named' => array('page')));

But it still only shows the first page of results regardless of what page I'm on. What do I need to do to make sure the page parameter is a named parameter? I'd rather not fiddle with it in my controller action, but rather let the route handle it.

Thank you very much in advance. :)

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.

No comments: