Drag And Drop Category Management With CakePHP
View full article here: Drag and drop category management with CakePHP and Jquery our visit our blog today at EndYourIf.com
Today’s article is going to walk you through creating a slick drag and drop with AJAX category management system.
CakePHP offers a really nice built-in tree management. In fact, at a bare minimum you simply need to create a table with 2 extra columns, tell your model to act like a “tree” and rather than doing a find(’all’) you do a generatetreelist() or a find(’threaded’) and CakePHP takes care of the rest.
After doing a quick test, I was quite impressed with what CakePHP did for me, but I was not satisified. I wanted to create a really slick category management system that I can re-use and show off. Well, in this tutorial I go about 90% of the way. The only thing I didn’t have time to finish was, rather than redrawing my tree through AJAX, use DHTML and dynamically update my tree after dragging and dropping. Don’t worry, I plan to finish this with a part two soon.
I know it’s not the most beautiful system in the word. But, I hope it drives the point home of how much potential there is with this system. To create all of the code below and do a bit of testing, it took about 3 hours total! A normal category management system of unlimited sub categories would probably take me a couple of days AND there is no way it could match the “coolness” factor of this application.
Also, in case the screen shots are not quite clear. To create a new category, type the name in the text box and drag the red rectangle above to where you want to place it. The category it will be placed in will be highlighted in yellow. If you wish to move a category or entire branch, simply drag it and move it to the new category.
Ok, let’s move on to the actual code. The first thing to do is create our categories table:
Code
CREATE TABLE `categories` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(255) NOT NULL, `parent_id` int(10) unsigned NOT NULL, `lft` int(10) unsigned NOT NULL, `rght` int(10) unsigned NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;If you’ve ever built a category system, the first three columns should look familiar. The key columns here though are the fourth and fifth columns, the lft and rght. CakePHP automatically deals with these columns for us whenever we save or delete data. For a detailed explaination, view this document from Mysql: http://dev.mysql.com/tech-resources/articles/hierarchical-data.html
Now that our table is created, the next thing I did was bake my model, controller, and views. After I baked all three, I had to update and remove a few things. First off our model, the simplest part of the process:
Code
As I mentioned before, the only thing special to note here is the “actAs” is set to “tree”. Next up is our controller, it’s also quite basic:
Code

