How do I get the Categories and the subcategories recursively using Magento 2? I was able to display all categories but the problem is I need to display it in a treelike manner such as below
- Default category
- Home
- About Us
- Products
- P-one
- SC-Four
- P-two
- SC-One
- SC-Two
- Site Map
- SC-One
- P-one
But what I'm getting is the displaying of all of this category. Is there a way to achieve the above sample? Right now my code looks like this
class Index extends \Magento\Framework\View\Element\Template
{
protected $_categoryCollectionFactory;
protected $_categoryHelper;
protected $_categoryRepository;
protected $_storeManager;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
array $data = []
)
{
$this->_categoryCollectionFactory = $categoryCollectionFactory;
$this->_categoryHelper = $categoryHelper;
$this->_categoryCategoryRepository = $categoryRepository;
$this->_storeManager = $storeManager;
$this->layerResolver = $layerResolver;
parent::__construct($context, $data);
}
/**
* Get category collection
*
* @param bool $isActive
* @param bool|int $level
* @param bool|string $sortBy
* @param bool|int $pageSize
* @return \Magento\Catalog\Model\ResourceModel\Category\Collection or array
*/
public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');
// Select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}
// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}
// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}
// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}
return $collection;
}
and in my phtml file I have this
$categories = $this->getCategoryCollection();
foreach ($categories as $category) {
echo $category->getName() . '<br />';
}
I'm not sure how to do about this and it would be great if I can also get a reference of any Magento 2 documentation where it teaches how to get different part of the site like the products and other stuff. Right now I have zero knowledge with Magento and I don't know any documentation/tutorial I can follow.
Would appreciate your help on this.