Filling a Select with Tree Behavoir

By Sean Culver (Snapp)
A quick tutorial on how to fill a Select box with a tree structure from a model that uses Tree behavior.
This is my first guide, i'll try to make it as good as possible, the topic is simple. I ran across the need to add an upload while allowing the users to choose a category.

To make this work its quite simple.

lets take a look at my Category model

/app/models/category.php

Model Class:

Download code <?php 
class Category extends AppModel {
    var 
$name 'Category';
    var 
$actsAs = array('Tree');
    var 
$order 'Category.lft ASC';    

}
?>
This model simple uses the Tree Behavior and sorts Ascending on the left values.

Suppose you wanted to use a drop box in the index view of your app, you would need to get the results from the db and then send them to the view in the proper format.
/app/controllers/categories_controller.php

Controller Class:

Download code <?php 
class CategoriesController extends AppController {

    var 
$name 'Categories';
    var 
$helpers = array('Form','Html','Javascript');
    
    function 
index() {           
        
$this->set('categoriesList',$this->Category->generateTreeList(null"{n}.Category.id""{n}.Category.name"'--'4)); 
    }


}
?>

I have used generateTreeList to automatically retrieve the results and format them to be used in the select box.

generateTreeList(1,2,3,4,5) accepts some parameters.

1 sql conditions array('field' =>'value',...)
2 The key used in generating the select
3 The Text used in generating the select
4 The Spacer used for children in the select
5 The number of Recursions through your tree.

Lastly we need to use it in our view

for this i'll just give you the code for the select box, you should use the form helper to create the form $form->create('categories/add') and close the form $form->end

View Template:

Download code
$form->select('Category', $categoriesList);

Thats pretty much it. I hope it could help some of you, if i'm wrong please let me know.

Sean