I want to add a free product to cart with another product. For that I wrote checkout_cart_product_add_after
event observer. My problem is, I don't get the updated cart subtotal(after adding first product, it returns subtotal as 0). This is my observer code.
namespace StwBuyXGetY\BuyXGetY\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;
class AddfreeProduct implements ObserverInterface
{
protected $_productRepository;
protected $_cart;
protected $formKey;
public function __construct(
\Magento\Checkout\Model\Cart $cart,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Data\Form\FormKey $formKey){
$this->cart = $cart;
$this->formKey = $formKey;
$this->logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$totals = $this->cart->getQuote()->getTotals();
$subtotal = $totals['subtotal']->getValue();
$this->logger->debug($subtotal);
}
}
Any help will be greatly appreciated.
Best Answer
We should use
\Magento\Checkout\Model\Session
:Try to get the totals: