Custom Prefixes and Named URL Arguments – CakePHP Gotcha

15 Jul
2009

Apparently custom prefixes and custom named arguments in URLs don’t mix all that well in good ol’ CakePHP. I’ve got a StatisticsController with some custom_-prefixed actions. So, in routes.php I added this line to parse the URLs:

Router::connect('/statistics/custom/:action/*', array('prefix' => 'custom', 'controller' => 'statistics', 'custom' => true));

Straightforward enough, right? And to generate a link with the $html helper, you just need to do pass the prefix as true, like so:

$html->link('Go here', array('controller' => 'statistics', 'action' => 'view', 'custom' => true));

That’ll generate your /statistics/custom/view link. But if you try to pass a custom named argument, for example:

$html->link('Go here', array('controller' => 'statistics', 'action' => 'view', 'custom' => true, 'Paginate' => 25));

You might think (hope?) that the generated link would be /statistics/custom/view/Paginate:25… but no. Thanks to the presence of the named Paginate argument, the code also interprets ‘custom’ as a named argument, resulting in the URL /statistics/custom_view/custom:1/Paginate:25/. So, it spits out the full method and also takes on a ‘custom’ named argument. Not what we want…

To solve this issue, you’ll need to define each and every named argument you intend to pass in your application at the top of your app/config/routes.php, like this:

Router::connectNamed(array('Paginate', 'page'));

Throw that line in your route file before any Router::connect() rules and your custom prefixes and named arguments will get along swimmingly. CakePHP will know to separate those named arguments from your custom prefixes, so you’ll get the /statistics/custom/view/Paginate::25 URL.

1 Response to Custom Prefixes and Named URL Arguments – CakePHP Gotcha

Avatar

Jamie Nay » Useful CakePHP Tutorial Roundup for July 17, 2009

July 17th, 2009 at 7:10 am

[...] – Nate (July 14, 2009) I’ve been struggling with prefix routing – see my recent post about prefix routing and named arguments – and just when I came up with a decent (but admittedly hackish) solution to deal with the issue, [...]

Comment Form

top