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
-
If you have found an answer please use arrows/checkmark to upvote/accept an answer. Thank you.sv3n– sv3n2018年12月10日 10:32:40 +00:00Commented Dec 10, 2018 at 10:32
3 Answers 3
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
-
Thanks! but... same error :)Fer González Blanco– Fer González Blanco2018年12月04日 14:07:38 +00:00Commented Dec 4, 2018 at 14:07
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.
-
Thanks for your awnser but... same result :)Fer González Blanco– Fer González Blanco2018年12月04日 13:58:27 +00:00Commented Dec 4, 2018 at 13:58
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;
}