2

I want to get the current shown category in \Magento\Theme\Block\Html\Topmenu.

When using the anti-pattern Objectmanager approach in phtml via:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$registry = $objectManager->get('\Magento\Framework\Registry');

Or using some dependency-injection via:

class Topmenu extends \Magento\Theme\Block\Html\Topmenu {
    protected $_registry;

    public function __construct(
        Template\Context $context,
        NodeFactory $nodeFactory,
        TreeFactory $treeFactory,
        array $data = [],
        \Magento\Framework\Registry $registry
    ) {
        $this->_registry = $registry;
        parent::__construct($context, $nodeFactory, $treeFactory, $data);
      }

    public function _prepareLayout(){
        return parent::_prepareLayout();
    }

    public function getRegistry() {
        return $this->_registry;
    }

    public function getCurrentCategory() {
       return $this->_registry->registry('current_category');
    }
}

I alway get a nearly empty Registry-Model like:

object(Magento\Framework\Registry)#128 (1) { ["_registry":"Magento\Framework\Registry":private]=> array(1) { ["use_page_cache_plugin"]=> bool(true) } }

What am I doing wrong that when I call "getCurrentCategory()" it is NULL?

Further thoughts: Is there a place where I have to do a kind of _initCategories()? Is the registry somehow restricted or private?

1
  • Is it also on category page or is it only on product page? Commented Mar 28, 2017 at 17:51

1 Answer 1

0

Thanks to a question from Elvin Risti I found the nobrainer here:

I expected the registry to contain at least the main category on home. But on category and product pages the registry does contain everything needed.

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.