Thursday, November 5, 2009

The only requirement is a working CakePHP application. You can refer to this post to help you get one.

Step 1: Create the table in your database

First we need to create a table to store our tree. To keep things a bit generic we create a simple table called 'Nodes'. There are various ways to extend this table with other functionality or data, but that is beyond the scope of this tutorial.

Step 2: Create the model

The model Node is defined as any other model in CakePHP. With the line var $actsAs = array('Tree'); we tell CakePHP to use this model as a tree.

Step 3: Create the controller

The controllers task is to take care of handling the data (adding, showing, updating, deleting, and more). At first we will create a controller with 2 functions, one called 'index' to display the tree and the other called 'add' to add items to the tree. The controller will be app/controllers/nodes_controller.php.

The index function is pretty straightforward, it uses the generatetreelist function to generate a formatted tree, and return it in an array.

The Add function is a bit more complex. It first checks if it received any data. If it did, it saves the data to the database and then redirects to the index again. If the add function did not receive any data, it will create the array needed to populate the 'Parent' select box in our Add screen (see below).

Step 4: Create the views

We now create 2 view files in the folder app/views/nodes/, which needs to be created first.

First there is a link back to the index. After that a new HTML Form of the type Node is create. It then add two fields, one for the Node name, the other to select the parent of the new node. The last function add the submit button with the text 'Add'.

You should now be able to show your tree, and add nodes to it. Actually you first need to add a node because there is nothing to display yet. In the next step we will add some more functionality to it, but this seems a good moment to check if it all works so far :) ...

Step 5: Adding more functionality

In this step we will add the posibility to edit and delete the nodes, as wel as move them up and down. We do this by adding some links to the Index page, add the edit view and add some functions to the controller.

First we update the file app/views/nodes/index.ctp so it looks like this:

The part that loops trough the nodelist is changed here. We define 4 URL's for the needed actions, and put them all in front of the Node name, seperated by a pipeline character. This is not the most elegant solution, but it will get the job done.

Next we add a view for the edit functionality by creating the file app/views/nodes/edit.ctp:

This view is mostly the same as add.ctp. Two differences: the edit view needs a hidden field called 'id', and the parent_id selectbox has a 'selected' parameter, which selects the right parent when in Edit mode.

In the last step we add four functions (edit, delete, moveup, movedown) to the Controller, app/controllers/nodes_controller.php, so it will look like this:

The first part of the edit function works much like the add function, it checks on received data and tries to save it. When there is no data received, it checks if there is a paramater called ID. If not it dies with an error message. If the parameter is given it fetches the node data, and gets the data needed to populate the 'Parent' select box, just like in the Add screen

The rest of the three functions are almost identical, and don't need any matching views as the code will redirect to the index page anyway. All these functions check if the parameter ID is passed, and dies with an error if not. If the parameter is given it selects the right node and runs the action.

Done!

This should be it, you should now have a tree created in CakePHP, with complete Create, Read, Update and Delete functionality (and even more)...

Good luck using this code, and please use the comments if you have any questions about it.

The only requirement is a working CakePHP application. You can refer to this post to help you get one.

Step 1: Create the table in your database

First we need to create a table to store our tree. To keep things a bit generic we create a simple table called 'Nodes'. There are various ways to extend this table with other functionality or data, but that is beyond the scope of this tutorial.

Step 2: Create the model

The model Node is defined as any other model in CakePHP. With the line var $actsAs = array('Tree'); we tell CakePHP to use this model as a tree.

Step 3: Create the controller

The controllers task is to take care of handling the data (adding, showing, updating, deleting, and more). At first we will create a controller with 2 functions, one called 'index' to display the tree and the other called 'add' to add items to the tree. The controller will be app/controllers/nodes_controller.php.

The index function is pretty straightforward, it uses the generatetreelist function to generate a formatted tree, and return it in an array.

The Add function is a bit more complex. It first checks if it received any data. If it did, it saves the data to the database and then redirects to the index again. If the add function did not receive any data, it will create the array needed to populate the 'Parent' select box in our Add screen (see below).

Step 4: Create the views

We now create 2 view files in the folder app/views/nodes/, which needs to be created first.

First there is a link back to the index. After that a new HTML Form of the type Node is create. It then add two fields, one for the Node name, the other to select the parent of the new node. The last function add the submit button with the text 'Add'.

You should now be able to show your tree, and add nodes to it. Actually you first need to add a node because there is nothing to display yet. In the next step we will add some more functionality to it, but this seems a good moment to check if it all works so far :) ...

Step 5: Adding more functionality

In this step we will add the posibility to edit and delete the nodes, as wel as move them up and down. We do this by adding some links to the Index page, add the edit view and add some functions to the controller.

First we update the file app/views/nodes/index.ctp so it looks like this:

The part that loops trough the nodelist is changed here. We define 4 URL's for the needed actions, and put them all in front of the Node name, seperated by a pipeline character. This is not the most elegant solution, but it will get the job done.

Next we add a view for the edit functionality by creating the file app/views/nodes/edit.ctp:

This view is mostly the same as add.ctp. Two differences: the edit view needs a hidden field called 'id', and the parent_id selectbox has a 'selected' parameter, which selects the right parent when in Edit mode.

In the last step we add four functions (edit, delete, moveup, movedown) to the Controller, app/controllers/nodes_controller.php, so it will look like this:

The first part of the edit function works much like the add function, it checks on received data and tries to save it. When there is no data received, it checks if there is a paramater called ID. If not it dies with an error message. If the parameter is given it fetches the node data, and gets the data needed to populate the 'Parent' select box, just like in the Add screen

The rest of the three functions are almost identical, and don't need any matching views as the code will redirect to the index page anyway. All these functions check if the parameter ID is passed, and dies with an error if not. If the parameter is given it selects the right node and runs the action.

Done!

This should be it, you should now have a tree created in CakePHP, with complete Create, Read, Update and Delete functionality (and even more)...

Good luck using this code, and please use the comments if you have any questions about it.

Very nice :)But you might want to change your sql statement and make all int fields unsigned. They're not going to be negative anyway.Also you could use the character set UTF-8 instead of Latin 1. CakePHP uses UTF-8 by default.

Thanks for the great tutorial! However, I'm using it with CakePHP 2.0 and needed to update my views. Where you have $html and $form, I needed to instead use $this->Html-> and $this->Form->. Hope that helps someone!

Nice tutorial I'm implementing it using drag n drop functionality, when I drag a node to different node I just change the parent id and when I also want to place the order where its dragged, can you provide the link u got for moveup n movedown func.

normally when I change the parent it put the that child in the last I want it to be placed where its dragged.

Very nice Treebehaviour article. Now, how about a tutorial on how to make the tree useful; for example if the tree was about recipe categories, how to organize a recipe system under it (as RecipeCetegories HABTM Recipes).

For some reason I could not determine (being new to PHP and CakePHP) the setFlash statements in movedown and moveup functions caused an error. Just as a temporary fix, I commented them out. Someone will have to help me with why they did not work in CakePHP 2.+.

PS: OK I discovered I have to literally add {n}.Node.reference if I wanted my reference field to show up in the generateTreeList. {n} refers to a numeric key for a DataSource (see https://groups.google.com/forum/?fromgroups#!topic/cake-php/6bK1XKgJnts).

What I still do not know is if this can be concatenated with another field(s). I tried using "{n}.Node.title . ' (' . {n}.Node.reference . ')'" -- but that did not work. I'm new to PHP, so I don't know if this is a PHP or a CakePHP issue.

I haven't had the time to look into this issue very long, but CakePHP offers the option to create 'Virtual Fields' ( http://book.cakephp.org/2.0/en/models/virtual-fields.html ). This might help you get the right information in the 'name' field.

If this is not what you want you might have to look at another way (beyond the generateTreeList method) to display the information.

By the way, I tend to go to the irc channel #cakephp on Freenode if I'm stuck at some point, most of the time you can get a quick response to your questions there.

Thank you, Bram, for all your help! ... for volunteering your time and expertise. Your answers have moved me along at a time when I was just about to give up on CakePHP altogether. I don't know quite how to describe it, but after weeks of work I had found the documentation to be very helpful on one level, but, on another, once I got beyond the tutorials, lacking in the information I needed to put the pieces together. So, I want you to know that your tutorial and your responses have helped me bridge that gap in a critical way. I had found the CakePHP IRC to be inactive when I visited several days ago, but I'll certainly give it another try. Thank you for encouraging that.