Question

Before we could do something like this:

$_categories = Mage::helper('catalog/category')->getStoreCategories();
foreach($_categories as $_category): 
    echo $_category->getName(); 
endforeach;

Plain and simple, just put it in a phtml file to list the categories. In Magento 2 it isn't as simple.

I've tried this, next to scrolling through 4 pages of Google searches for every possible solution ever. None of it works. I figure there is something wrong with my reasoning towards the new CMS. I probably need to see the logic in the structure of this code.

Can anyone please enlighten me on how to list all the stores categories in a phtml file like the example above?

Was it helpful?

Solution

if you want to achieve results with braking a couple important customization rules, then you can do almost the same as you did in Magento 1:

$_categories = $this->helper('Magento\Catalog\Helper\Category')
                    ->getStoreCategories();
foreach($_categories as $_category): 
    echo $_category->getName(); 
endforeach;

This will work since all PHTML templates in M2 are being rendered in the context of \Magento\Framework\View\TemplateEngine\Php class/object (so $this is pointing to this object), and category helper is yet available in M2.

But if you want to do it right, then you'd better to create your own block class and define appropriate dependencies for your block class (in this case it could be either same helper, or better to use Catalog module API instead: e.g. Magento\Catalog\Api\CategoryManagementInterface::getTree)

And you definitely don't need to rewrite several classes, or write several modules or do complete rewrite of the system.

OTHER TIPS

Thanks to V Korotun's answer I got this piece to work:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();       
$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active',1)
                ->setOrder('position', 'ASC');

foreach ($categories as $category) :
    echo $category->getName();
endforeach;
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top