Magento 2 : Fatal error: Uncaught Error: Call to a member function dispatch() | Store Information
-
04-10-2020 - |
Question
I'm trying to get store information which are set in backend like email,contact,address etc...(I've taken reference from here : https://magento.stackexchange.com/a/125359/39607 )
To do so I've created a module
Following is my block file...
Contact.php
<?php
namespace Vendor\Module\Block;
class Contact extends \Magento\Framework\View\Element\Template
{
protected $_storeInfo;
public function __construct(
\Magento\Store\Model\Information $storeInfo
)
{
$this->_storeInfo = $storeInfo;
}
public function getPhoneNumber()
{
return $this->_storeInfo->getInformationObject()->getPhone();
}
}
And in my phtml I'm calling like this :
<?php
echo "Phone: ".$block->getPhoneNumber();
?>
But it's not working and showing me an error :
( ! ) Fatal error: Uncaught Error: Call to a member function dispatch() on null in vendor\magento\framework\View\Element\AbstractBlock.php on line 644 ( ! ) Error: Call to a member function dispatch() on null in vendor\magento\framework\View\Element\AbstractBlock.php on line 644
What can be the issue here??
Solution 2
Well, I've done in following way...But I don't it's proper way to do so or not...
namespace Vendor\Module\Block;
class Contact extends \Magento\Framework\View\Element\Template
{
protected $_storeInfo;
protected $_storeManagerInterface;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Store\Model\Information $storeInfo,
array $data = []
)
{
$this->_storeInfo = $storeInfo;
parent::__construct($context, $data);
}
public function getPhoneNumber()
{
return $this->_storeInfo->getStoreInformationObject($this->_storeManager->getStore())->getPhone();
}
and in template file I've called
echo $block->getPhoneNumber();
UPDATE:
We don't need to use \Magento\Store\Model\StoreManagerInterface
as it's already in parent class. We can directly use it vai $this->_storeManager
OTHER TIPS
It's because your constructor does not match the parent block constructor. (the ...
in my answer you linked are important).
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Store\Model\Information $storeInfo,
array $data = []
)
{
$this->_storeInfo = $storeInfo;
parent::__construct($context, $data);
}
public function __construct(\Magento\Framework\View\Element\Template\Context $context,
\Magento\Store\Model\Information $storeInfo,
\Magento\Store\Model\StoreManagerInterface $storeManager ,
array $data = [] ) {
$this->_storeInfo = $storeInfo;
$this->_storeManager = $storeManager;
parent::__construct($context, $data);
}
Make sure you are working in developer mode and clear your generation folder by
rm -rf var/generation/*
did you tried like this?
public function getPhoneNumber()
{
return $this->_storeInfo->getStoreInformationObject($this->_storeManager->getStore())->getPhone();
}