Why is DI working in controller but not in Blocks?
-
06-10-2020 - |
Question
I was trying my hand on Magento 2. I am able to get the checkout session data inside a controller by injecting \Magento\Checkout\Model\Session $checkoutSession,
in controllers construct method.
But when I try to do the same in a Block class, Im unable to get any data from check out session.
<?php
namespace Company\Hello\Block;
class Main extends \Magento\Framework\View\Element\Template
{
protected $_checkoutSession;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Company\Hello\Model\Test $model,
\Magento\Framework\App\Request\Http $request,
\Magento\Checkout\Model\Session $checkoutSession
)
{
$this->_model = $model;
$this->_request = $request;
$this->_checkoutSession = $checkoutSession;
parent::__construct($context);
}
protected function _prepareLayout()
{
// print_r($this->_request->getParams());
// exit;
// $this->_model->getDbData();
$this->setCntnt(__('Hello World 2.0'));
}
public function getAddedProduct()
{
foreach ($this->_checkoutSession->getQuote()->getAllVisibleItems() as $item) {
echo $item->getName();
}
exit('block class');
}
}
Whereas I am able to access the object ($this->_checkoutSession
) but can't get any value.
I call the method
getAddedProduct()
in the template file
can someone clarify this please?
Solution
You need to inject Checkout session and need to create()
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Checkout\Model\SessionFactory $session
) {
$this->session= $session;
parent::__construct($context);
}
then use getAllVisibleItems
$checkout = $this->session->create()->getQuote();
foreach ($checkout->getAllVisibleItems() as $item) {
echo $item->getName();
}
if work then plz accept the answere.
OTHER TIPS
In your construct method, add $this->_isScopePrivate = true;
. Take a look: vendor/magento/module-checkout/Block/Onepage/Link.php
You can try cacheable="false"
in your layout xml also.
Read more: How do disable caching of custom block on product view page?