2

I get this error in a block that I am developing to get current category. any ideas?

class CurrentCategory extends \Magento\Framework\View\Element\Template
{
protected $_registry;
public function __construct(
 \Magento\Framework\Registry $registry
)
{
 $this->_registry = $registry;
}
public function getCurrentCategory()
{
 return $this->_registry->registry('current_category');
}

PHP Fatal error: Uncaught Error: Call to a member function dispatch() on null in /vendor/magento/framework/View/Element/AbstractBlock.php:652

Manashvi Birla
8,8739 gold badges29 silver badges53 bronze badges
asked Dec 4, 2018 at 12:38
1
  • If you have found an answer please use arrows/checkmark to upvote/accept an answer. Thank you. Commented Dec 10, 2018 at 10:32

3 Answers 3

0

Try below code

class CurrentCategory extends \Magento\Framework\View\Element\Template
{
protected $_registry;
public function __construct(
 \Magento\Framework\View\Element\Template\Context $context,
 \Magento\Framework\Registry $registry
)
{
 parent::__construct($context);
 $this->_registry = $registry;
}
public function getCurrentCategory()
{
 return $this->_registry->registry('current_category');
}

run upgrade, compile and deploy command and clear cache

Rohan Hapani
17.6k9 gold badges57 silver badges99 bronze badges
answered Dec 4, 2018 at 13:02
1
  • Thanks! but... same error :) Commented Dec 4, 2018 at 14:07
0

You can simply inherit (or use, if you don't want to add functionality) from \Magento\Catalog\Block\Category\View instead of \Magento\Framework\View\Element\Template to get access to the getCurrentCategory() method.

answered Dec 4, 2018 at 13:15
1
  • Thanks for your awnser but... same result :) Commented Dec 4, 2018 at 13:58
0

You constructor has to match the parent one ... please try this:

public function __construct
(
 \Magento\Framework\View\Element\Template\Context $context,
 \Magento\Framework\Registry $registry
 array $data = []
) {
 parent::__construct($context, $data);
 $this->_registry = $registry;
}
answered Dec 4, 2018 at 14:30
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.