How to get category tree in Magento 2?
I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found \Magento\Catalog\Block\Adminhtml\Category\Tree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.
I created a block file where I have injected the above class as:
<?php
namespace Vendor\Module\Block;
class CategoriesColle extends \Magento\Framework\View\Element\Template
{
...
protected $adminCategoryTree;
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Catalog\Helper\Category $categoryHelper
* @param array $data
*/
public function __construct(
...
\Magento\Catalog\Block\Adminhtml\Category\Tree $adminCategoryTree
)
{
...
$this->adminCategoryTree = $adminCategoryTree;
}
public function getTree()
{
return $this->adminCategoryTree->getTree();
}
...
}
The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.