George Whitcher

CakePHP Easy Sorting with Pagination

CakePHP Easy Sorting with Pagination

I haven’t posted many code snippets in a long time so here is a very usefull piece of CakePHP and Ajax I made for sorting with pagination. I had to do this for my current job and I was rather impressed at it’s usefullness and figured others may benifit from it as well. This is a step up from the Tree Behavior sorting that comes with CakePHP and in my opinion is better. That is just my opinion though. I am sure the Tree Behavior that comes with CakePHP for sorting is great but I held my nose up at having to add 2 new database fields to my table. I like the idea of one single field to control position.

Below is the code to my Gallery but can be used for anything with some slight modification. I had to save it in a GIST because the HTML wasn’t displaying properly in the <pre></pre> tag. This is a working example of pagination, click and drag reordering, moving items up, and moving items down and saving the changes to the database. The HTML also uses Bootstrap 3 but works without as well. This is a great way to order items that are paginated using CakePHP. It is also setup with a bootstrap modal if you want. Otherwise just delete the modal code, the preview button, and the view head from the table.

The code is pretty self explanatory. Adjust it to your table and add a field named “position” to your table. Either click and drag your item to reorder them or click the up arrow or down arrow to move accordingly. That’s it! Enjoy!

Sharing is caring!