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();  


enter image description here

enter image description here

Any help will be greatly appreciated.


We should use \Magento\Checkout\Model\Session:

 * @var \Magento\Checkout\Model\Session
protected $_checkoutSession;

public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession,
    $this->_checkoutSession = $checkoutSession;


Try to get the totals:

//Get totals
//Get sub total.
| improve this answer | |
  • Thanks Khoa, for your answer. But, my bad luck, it is not working :( – Keerthana Aug 26 '16 at 6:27
  • You tried to dump out the data? Actually, your question also make me confused. You want to know the collect total data or you want to add an extra fee? – Khoa TruongDinh Aug 26 '16 at 6:30
  • I just want to get cart subtotal. But in checkout_cart_product_add_after observer I don't get it by using the code I mentioned above. – Keerthana Aug 26 '16 at 6:35
  • You tried to dump out this data? – Khoa TruongDinh Aug 26 '16 at 6:38
  • Yes, I have used logger to print this data. But it displays 0. – Keerthana Aug 26 '16 at 6:42

You can try

$this->_cartTotalRepository using \Magento\Quote\Model\Cart\CartTotalRepository

$totals = $this->_cartTotalRepository->get($this->cart->getQuote()->getId());
// Subtotal
$subtotal = (float) $totals->getSubtotal();

Let me know if you have any question.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.