CakePHP paginator sorting problem solved!

I’ll keep this brief, because I need to get back to writing code, but I wanted to share the solution I found to a CakePHP problem that has been nagging me for a while and for which I had never found a simple resolution.

I’m using the $paginator->sort() method to create links in the column headers for tables of paginated search results in my CMS. The method works great, except for one small problem: I could never get it to reverse the order. Intuitively, with links like these, you should be able to click them once to sort in ascending order, and then click again to reverse into descending order. But the reverse was never working for me.

Some research showed that you can pass in all sorts of options to the method, but I wanted to avoid having to make a change like that to about a dozen views; plus, it just didn’t seem right — the method is supposed to do the reverse by default.

At last I have discovered the source of my trouble: you need to explicitly name the model in the parameter that defines the sort field. I’ve been getting more diligent about always naming my models explicitly, but back when I set up these paginated tables (which was about the first thing I did in writing the application), I wasn’t doing it yet. Adding in the model, the reverse order on a second click works perfectly. Here’s a before-and-after example to illustrate the problem and its resolution.

Before:

<?php echo $paginator->sort('Title', 'title'); ?>

After:

<?php echo $paginator->sort('Title', 'Article.title'); ?>