How to get child categories from selected parent category when "Use
Flat Catalog Category" is enabled?
I need to create a small menu which displays all sub-categories of current category in a custom menu.
To get sub-categories of the current category, I extended class Magento\Catalog\Block\Navigation
and created a method which returns sub-categories (identifier of the current category is passed in $parent
parameter):
namespace Company\MyNav\Block;
class MyNav extends \Magento\Catalog\Block\Navigation
{
public function getCategoryChildren($parent)
{
$category = ObjectManager::getInstance()->create('Magento\Catalog\Model\Category');
$subCategories = $category->getCategories($parent);
return $subCategories;
}
// ...
}
It all works great, method getCategories
from Magento\Catalog\Model\Category
returns all sub-categories (also from all lower levels) of the selected parent category.
But as soon as I enable "Use Flat Catalog Category" option in admin, method getCategories
returns entire tree of categories instead of only the children of the selected category.
-
Shouldn't the same code give the same results no matter if flat categories are enabled or disabled? Is this a bug in Magento 2?
-
Are there any additional steps needed to make this code work even flat categories field is enabled?
Best Answer
You can use
getChildren
to get child category data in your block evenUse Flat Catalog Category
is enabled.For example
Inside the phtml template.
Out put
Reference link for more details.
Recommended to pass classes to constructor as a dependency.
Hope it helps.