XF 2.1 How to get node children from a nodelist?

asprin

Active member
On an external PHP script, I'm using the following the code to fetch the nodes. My requirement is to display a tree-like structure of category-forum on a page so that a user can select a forum from the list. The code is as follows:

PHP:
$nodeRepo = \XF::app()->repository('XF:Node');
$nodeList = $nodeRepo->createNodeTree($nodeRepo->getNodeList());

foreach($nodeList as $obj)
{                    
    print_r($obj);
}

This prints out the following:
1578805120784.png

I'm able to access the node values with $obj['record']->title but how would I get the children of that node?
 
Last edited:
Have a look at the methods available on \XF\Tree (and \XF\SubTree). In particular, there is children() which takes an option node ID and returns a sub-tree of its children, if that's what you wanted.
 
Have a look at the methods available on \XF\Tree (and \XF\SubTree). In particular, there is children() which takes an option node ID and returns a sub-tree of its children, if that's what you wanted.
Thanks for that. I went through the methods and tried to call them. The returned data is again in a complex form that I'm struggling to comprehend. But let me see if I can figure it out my more trials and errors.
 
Alright! I've got it. Thanks @Jeremy P for pointing me in the right direction. I'll list it out in case someone finds it helpful.

Using the method declared in \XF\Tree, I used the following in my code:
PHP:
$nodeRepo = \XF::app()->repository('XF:Node');
$nodeList = $nodeRepo->createNodeTree($nodeRepo->getNodeList());
$allnodes = $nodeList->getDescendants();
print_r($allnodes); // printed all nodes without following an heirarchy

Then I used the following:
PHP:
$simple_nodes = $this->buildTree($allnodes);
print_r($simple_nodes);


// definition of buildTree()
public function buildTree($elements, $parentId = 0)
{
    $branch = array();     
    foreach ($elements as $element)
    {         
        if ($element->parent_node_id == $parentId)
        {
            $children = $this->buildTree($elements, $element->node_id);
            if ($children)
            {
                $descendants = $children;
            }
            else
            {
                $descendants = array();
            }
            $meta = array('title'=>$element->title, 'type' => $element->node_type_id, 'id'=>$element->node_id, 'children'=>$descendants);
            $branch[] = $meta;
        }
    }
    return $branch;
}

So the end result was that this:
1578903248491.png

was converted to:
1578903342395.png
1578903486121.png
1578903552075.png

I can now generate the appropriate HTML to form a tree structure from the above PHP array.[/ICODE]
 
Top Bottom