0

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?

2 Answers 2

2

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.

2
  • You're right about that last part - that was the frustration talking ;) Your piece of code, however, lands me with a blank page. But it got me on the right track for a solution. Thanks for the info on 'the right way' - this is just something I have to get myself familiarized with!
    – Asitis
    Commented Jun 15, 2016 at 10:21
  • I've updated code snippet, There was excessive "ifend;" at the end, copied from your original post, btw :)
    – user40988
    Commented Jun 15, 2016 at 10:42
0

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.