Display Acts As Tree Recursively

Having in the controller

$this->Models =& $this->Model->findAll();

where Model acts as a tree, you can have a simple and flexible helper function for displaying trees as a list by adding this to your helper:

function display_tree_recursive($tree, $parent_id = null, $options = array())
{
    if(!empty($tree)){
        foreach(array_keys($tree) as $k){
            $Node =& $tree[$k];
            if($Node->parent_id == $parent_id){
                @$result .= "<li>";
                $result .= $this->link_to_node($Node, $options);
                $result .= $this->display_tree_recursive($tree, $Node->id);
                $result .= "</li>\n";
            }
        }
        if(!empty($result)){return "\n<ul>\n".$result."</ul>\n";}
    }
}
 
function link_to_node($Node, $options = array())
{
    $default_options = array(
        'display' => 'name',
        'id' => $Node->id,
        'controller'=> AkInflector::underscore($Node->getModelName()),
        'action' => 'show'
        );
    $options = array_merge($default_options, $options);
    $display = $Node->get($options['display']);
    unset($options['display']);
    return $this->_controller->url_helper->link_to($display, $options);
}

Now for creating lists from acts_as_tree and acts_as_list you just need to call in your view

<%= display_tree_recursive Models %>

or

<? $children = $Model->tree->getChildren(); ?>
{?children}
    <h2>_{Model children}</h2>
    <div id="children"><%= display_tree_recursive children, Model.id %></div>
{end}

Following the Akelos way, you can modify the default behavior using the $options array.

 
display-acts-as-tree-recursively.txt · Last modified: 2008/05/03 14:08 by thijs