How to Inject a new Class to Overridden Class using Preference
-
14-04-2021 - |
Question
I want to override __prepareLayout
function from 'Magento\Sales\Block\Order\History' so I used the preference.
In my di.xml
<preference for="Magento\Sales\Block\Order\History" type="Custom\Module\Block\Order\History"/>
In my History.php
class History extends \Magento\Sales\Block\Order\History
{
protected function _prepareLayout()
{
parent::_prepareLayout();
$this->setTemplate('Custom_Module::order/history.phtml');
return $this;
}
}
To this point my code is working fine now I want to inject custom Helper in this class.
So I added this-
public function __construct(
\Custom\Module\Helper\Data $helper
) {
$this->helper = $helper;
}
After Injecting Class the code is not working. I have the option to use ObjectManager
, but it is not recommended, so I preferred to ask from Community if you have any better Option!
La solution
you need to call parent constructor also with required parameters
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
\Magento\Customer\Model\Session $customerSession,
\Magento\Sales\Model\Order\Config $orderConfig,
\Custom\Module\Helper\Data $helper
) {
$this->_orderCollectionFactory = $orderCollectionFactory;
$this->_customerSession = $customerSession;
$this->_orderConfig = $orderConfig;
$this->helper = $helper;
parent::__construct($context, $orderCollectionFactory, $customerSession, $orderConfig);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange