How to manipulate the child items of the tree menu in cakephp 3?

自古美人都是妖i 提交于 2020-06-23 14:13:32

问题


I'm having doubts about manipulating the child menu items to improve the display style.

I am currently generating according to documentation:

function index() 
   {
     $list = $this->Categorias->find('threaded')->toArray(); 
     $this->set('list', $list);
   }    

$renderItems = function($items) use (&$renderItems)
{
    echo '<ul>';
    foreach ($items as $item) {
        echo '<li>';
        echo h($item->name);

        if ($item->children) {
            $renderItems($item->children); // < recursion
        }

        echo '</li>';
    }
    echo '</ul>';
};

$renderItems($list);

But the display is in error.. The display is in this format:

I appreciate any comments!


回答1:


As mentioned in the tree behavior docs, if you want to use threaded results, then you need some kind of recursive functionality to iterate not only over the top level items (which your example is doing), but also over the nested child items.

Also note that using the children finder as in your example, will only retrieve the children of the node with the specified primary key, ie it won't retrieve their parent node, also if the table contains multiple root nodes, they wouldn't be retrieved either. So depending on your data you might need to use only the threaded finder.

That being said, the children of an item are nested under the children property/key, so a basic example could look like this:

$renderItems = function($items) use (&$renderItems)
{
    echo '<ul>';
    foreach ($items as $item) {
        echo '<li>';
        echo h($item->name);

        if ($item->children) {
            $renderItems($item->children); // < recursion
        }

        echo '</li>';
    }
    echo '</ul>';
};

$renderItems($list);

That would create a nested list like this (without the formatting/indenting of course):

<ul>
    <li>
        Fun
        <ul>
            <li>
                Sport
                <ul>
                    <li>Surfing</li>
                    <li>Skating</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>
        Trips
        <ul>
            <li>National</li>
            <li>International</li>
        </ul>
    </li>
</ul>

See also

  • Cookbook > Database Access & ORM > Behaviors > Tree


来源:https://stackoverflow.com/questions/62244738/how-to-manipulate-the-child-items-of-the-tree-menu-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!