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($Node->tree->getChildren(), $Node->id, $options);
                $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, :display => 'title' %></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/19 15:31 by 79.84.234.134
 

The Akelos Framework was created by Bermi Ferrer and other contributors.
Potions of the code and documentation have been ported from Ruby on Rails.

The Akelos Framework is released under the LGPL license.

"Akelos", "Akelos Framework", and the Akelos logo are trademarks of Bermi Labs All rights reserved.

Wiki driven by DokuWiki