I have tried many methods to get cart items inside plugin for "Magento\ConfigurableProduct\Block\Product\View\Type\Configurable"
. I am trying to add additional cart item data to the "getJsonConfig" function.
No matter what I do, the cart always seems to be empty even though there are items in the cart.
<?php
namespace VENDORNAME\VENDORMODULE\Plugin\ConfigurableProduct\Product\View\Type;
use VENDORNAME\VENDORMODULE\Helper\Data as Helper;
class Configurable
{
protected $_helper;
protected $_jsonDecoder;
protected $_jsonEncoder;
protected $_customerSession;
protected $_checkoutSession;
protected $_cart;
protected $_cartHelper;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
Helper $helper,
\Magento\Framework\Json\DecoderInterface $jsonDecoder,
\Magento\Framework\Json\EncoderInterface $jsonEncoder,
\Magento\Customer\Model\Session $customerSession,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Checkout\Model\Cart $cart,
\Magento\Checkout\Helper\Cart $cartHelper,
array $data = []
) {
$this->_helper = $helper;
$this->_jsonDecoder = $jsonDecoder;
$this->_jsonEncoder = $jsonEncoder;
$this->_customerSession = $customerSession;
$this->_checkoutSession = $checkoutSession;
$this->_cart = $cart;
$this->_cartHelper = $cartHelper;
}
protected function _getCartProducts() {
$cartProducts = array();
$cartItems = $this->_checkoutSession->getQuote()->getAllItems();
if($cartItems && sizeof($cartItems)) {
foreach($cartItems as $item) {
if($item->getProductType() == 'simple' && $item->getParentItemId()) {
$cartProducts[$item->getProductId()] = $item->getQty();
}
}
}
return $cartProducts;
}
public function afterGetJsonConfig($subject, $result) {
$config = $this->_jsonDecoder->decode($result);
$config['cart'] = $this->_getCartProducts();
return $this->_jsonEncoder->encode($config);
}
}
Anyone have any ideas how to retrieve the cart items here? Or why it is missing? Do I need a $cartId variable or something to load the cart first? Is it possible this has something to do with caching?
I have no idea why the cart appears empty here.
Thanks in advance