CakePHP Tree behavior Full Guide:
CakePHP Tree Behavior is very Useful in creating a Hierarchical data.The CakePHP tree behavior is very efficient than Other Techniques.Tree Behavior can easily handle unlimited number if subcategories and very useful for multilevel menus .It is Based on MPPT Logic , But CakePHP handles every thing for you ,you dont have to completely understand this MPPT logic for using CakePHP Tree Behavior.
So today we got a Full Guide on cakePHP tree Behavior. Lets Get Moving and Understand the CakePHP tree Behavior.
CakePHP Tree Behavior Full Guide::Tutorial-
For Understanding the CakePHP Tree Behavior we’ll create a new cakePHP application ,which will have a database table named categories ,with Category Model ,Categories Controller and The view files (add.ctp ,edit.ctp , index.ctp) .So firstly lets see the Schema for the database which is required here.
cakePHP Tree Behavior Full Tutorial :: Database Schema-
Firslty we’ll create a new database for our new cakePHP and a new table inside that named ‘Categories’.IN the categories table we’ll need to have following Columns:
|
Column |
Type | Null | Default |
| id | int(10) | No | |
| parent_id | int(10) | Yes | NULL |
| lft | int(10) | Yes | NULL |
| rght | int(10) | Yes | NULL |
| name | varchar(255) | Yes |
The Above is the Table Structure for categories table.You can create it Or use the SQL below to create the table for you.
CREATE TABLE categories ( id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT, parent_id INTEGER(10) DEFAULT NULL, lft INTEGER(10) DEFAULT NULL, rght INTEGER(10) DEFAULT NULL, name VARCHAR(255) DEFAULT '', PRIMARY KEY (id) );
Now After Creating The Table .we’ll add some data to it.Run the query below in phpMyAdmin to add some data to your categories table.
INSERT INTO `categories` (`id`, `parent_id`, `lft`, `rght`, `name`) VALUES (27, 0, 1, 32, 'Main Menu'), (28, 27, 2, 11, 'Web Development'), (29, 27, 12, 17, 'Web Design'), (30, 35, 6, 7, 'Zend'), (31, 27, 18, 25, 'Cooking'), (32, 31, 19, 20, 'Cuisines'), (33, 31, 21, 22, 'Snaks'), (34, 28, 3, 4, 'PHP'), (35, 28, 5, 10, 'Frameworks'), (36, 31, 23, 24, 'Beverages'), (37, 29, 13, 14, 'Photoshop'), (38, 29, 15, 16, 'Flash'), (39, 35, 8, 9, 'cakePHP'), (40, 27, 26, 31, 'Friends'), (41, 40, 27, 28, 'Rachel'), (42, 40, 29, 30, 'Rubil');
Now that your table has data and now we set up our model.
cakePHP Tree Behavior Full Tutorial :: Model Setup-
Now Move To next step for understanding CakePHP Tree Behavior.and we set up Our MODEL for our tree behaviour . The line “acts as=array(‘Tree’)” Tells Category Model to use Tree Behavior.
<?php
class Category extends AppModel {
var $name = 'Category';
var $actsAs = array('Tree');
}
?>
That is all we need to do in the Our Model Now we setup our categories controller.Lets see the categories controller.
cakePHP Tree Behavior Full Guide :: Controller Setup-
Now We create the controller for our category model.Here You’ll see that controller covers all the action to demonstrate the cakePHP Tree Behavior.
<?php
class CategoriesController extends AppController {
var $name = 'Categories';
function index() {
$Categorylist = $this->Category->generatetreelist(null,null,null," - ");
$this->set(compact('Categorylist'));
}
function add() {
if (!empty($this->data)) {
$this->Category->save($this->data);
$this->redirect(array('action'=>'index'));
} else {
$parents[0] = "[ No Parent ]";
$Categorylist = $this->Category->generatetreelist(null,null,null," - ");
if($Categorylist){
foreach ($Categorylist as $key=>$value){
$parents[$key] = $value;
}
$this->set(compact('parents'));
}
}
}
function edit($id=null) {
if (!empty($this->data)) {
if($this->Category->save($this->data)==false)
$this->Session->setFlash('Error saving Category.');
$this->redirect(array('action'=>'index'));
} else {
if($id==null) die("No ID received");
$this->data = $this->Category->read(null, $id);
$parents[0] = "[ No Parent ]";
$Categorylist = $this->Category->generatetreelist(null,null,null," - ");
if($Categorylist)
foreach ($Categorylist as $key=>$value)
$parents[$key] = $value;
$this->set(compact('parents'));
}
}
function delete($id=null) {
if($id==null)
die("No ID received");
$this->Category->id=$id;
if($this->Category->delete()==false)
$this->Session->setFlash('The Category could not be deleted.');
$this->redirect(array('action'=>'index'));
}
function moveup($id=null) {
if($id==null)
die("No ID received");
$this->Category->id=$id;
if($this->Category->moveup()==false)
$this->Session->setFlash('The Category could not be moved up.');
$this->redirect(array('action'=>'index'));
}
function movedown($id=null) {
if($id==null)
die("No ID received");
$this->Category->id=$id;
if($this->Category->movedown()==false)
$this->Session->setFlash('The Category could not be moved down.');
$this->redirect(array('action'=>'index'));
}
function removeNode($id=null){
if($id==null)
die("Nothing to Remove");
if($this->Category->removeFromTree($id)==false)
$this->Session->setFlash('The Category can\'t be removed.');
$this->redirect(array('action'=>'index'));
}
}
?>
cakePHP Tree Behavior Full Guide ::View Setup-
Now We create our view files for the controller actions we have created earlier.WE created three actions add,edit and index .so we gonna create index.ctp,add.ctp and edit .ctp .WE do not need to create views for the moveup , movedown, delete and removeNode Functions.
<?php
echo $html->link("Add Category",array('action'=>'add'));
echo "<ul>";
foreach($Categorylist as $key=>$value){
$editurl = $html->link("Edit", array('action'=>'edit', $key),array('style'=>'font-weight:lighter;font-size:9px;color:green;','title'=>'Edit This Node'));
$upurl = $html->link("Up", array('action'=>'moveup', $key),array('style'=>'font-weight:lighter;font-size:9px;color:green;','title'=>'Move Up the Tree'));
$downurl = $html->link("Down", array('action'=>'movedown', $key),array('style'=>'font-weight:lighter;font-size:9px;color:green;','title'=>'Move Down the Tree'));
$deleteurl = $html->link("Delete", array('action'=>'delete', $key),array('style'=>'font-weight:lighter;font-size:9px;color:green;','title'=>'Delete the Node from the Tree'));
$removeurl =$html->link("Remove From Tree",array('action'=>'removeNode',$key),array('style'=>'font-weight:lighter;font-size:9px;color:#b3b3b3;','title'=>'Remove the Node from the Tree'));
echo "<li><sub>-$editurl-$upurl-$downurl-$deleteurl- </sub><span style='color:red;'>$value</span> <sup>$removeurl</sup></li>";
}
echo "</ul>";
?>
<?php
echo $html->link('Back',array('action'=>'index'));
echo $form->create('Category');
echo $form->input('name',array('label'=>'Name'));
echo $form->input('parent_id',array('label'=>'Parent'));
echo $form->end('Add');
?>
<?php
echo $html->link('Back',array('action'=>'index'));
echo $form->create('Category');
echo $form->hidden('id');
echo $form->input('name');
echo $form->input('parent_id', array('selected'=>$this->data['Category']['parent_id']));
echo $form->end('Update');
?>
After that You’ll be able to get CakePHP Tree Behavior demo application to work.Then You can easily Understand It.You’ll able to create,delete ,update tree items and more you’ll be able to move up move down and remove items from the tree.Now I’ll define which Function i have used here.
cakePHP Tree Behavior Full Tutorial ::Cake Tree Methods-
Here are Cake Tree methods used with the Description.
- generatetreelist($conditions=null, $keyPath=null, $valuePath=null, $spacer= ‘_’, $recursive=null) – This is function used to print out the Tree Structure.
- movedown() – Used to move down a node .
- moveup() -Used to move up a node.
- removeFromTree($id=null, $delete=false) – this function can perform two tasks,deleting and removing node from tree.
That was all ! Tnx for vising Design Aeon Web development Blog.Keep Vising.

Hi Ramandeep:
Thank you for you r help (time and expertise). Does this apply to CakePHP 1.3 only? I cannot get it to work with CakePHP 2.2. I’m wondering if there were some changes that I need to be aware of (e.g., $this->$html-> instead of just $html->, etc.
If so, it would be wonderful of you to show the changes.
Kevin
yeah its for cake1.3,,,There will be minor changes for 2.0 i guess
Thanks for this great Tutorial, helps a lot!
For the Cakephp 2.1 you just need to change the following commands:
In the views:
Change $html->link …. to $this->html->link….
In the controller:
Change generatetreelist to generateTreeList
Change moveup() to moveUp()
Change movedown() to moveDown()
And it works great for CakePHP 2.1 )
Regards,
Bettina
Thanks a lot Ramandeep!
I was looking for this dynamic menu but there was nothing… until I found you!
I’m trying to build a website using cakephp with a homemade CMS.
That’s quite a task knowing that I’m just a beginner and I’m looking for concrete tutorials.
However, I’d like to put an authorization with user name and password to complete your tutorial. I’d better get started then!
Again, thanks for your work!
Nice Post, so helpful post
Many thanks Ramandeep, helped me resolve a problem I had with static menus.
As Bettina mentioned above, code works fine CakePHP 2.x once you update the Views and Controller.