George Whitcher

Dad, Web Developer, Software Engineer, Graphic Artist, Snowboarder, Musician, Gamer, Nerd

CakePHP Easy Sorting with Pagination

Posted in Code
January 4, 2017 05:05:09 PM
Published by
Leave your thoughts

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!

https://gist.github.com/gwhitcher/f234185ba2cafd982047195fcd3e180a#file-gallerycontroller-php

https://gist.github.com/gwhitcher/f234185ba2cafd982047195fcd3e180a#file-index-php

 

 

Article written by:

Hi! My name is George Whitcher and I am a developer from the South Shore of MA.  When I am not busy being a dad I like to play video games, play/write music, snowboard, and skateboard.