1

I have created an observer for customer_login event which requests the current cart contents. I have tried to use (as indicated in other posts in this forum):

public function __construct(
        ...
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Checkout\Model\Cart $cart
) {
    ...
    $this->_checkoutSession = $checkoutSession;
    $this->_cart            = $cart;
}

and

public function execute(\Magento\Framework\Event\Observer $observer)
{
    ...
    $quote = $this->_checkoutSession->getQuote();
    $contents = $quote->getAllItems();  //Have tried getAllVisibleItems() too.

or

public function execute(\Magento\Framework\Event\Observer $observer)
{
    ...
    $quote = $this->_cart->getQuote();
    $contents = $quote->getAllItems();

In each case, the code works for the 'normal' situation and $contents is correct.

However, a false situation occurs where the customer logs in, adds product(s) and logs out - or closes the window without completing the purchase

If they then return to the store, add a product before logging back in, the login observer only picks up the new product whilst the cart on screen shows the entire cart - including the original products that were left in the cart.

It makes sense to add the old product back to the cart but I'd like to pick the entire product list up with my $quote->getAllItems()...

Is this possible? Do I need a second observer to act later in the process? (And if so, is there a standard event available?)

Interestingly, if I have a second observer checkout_cart_save_after, which gets the cart details in the same way, the complete list is returned...

This makes me think the cart is not yet updated when the customer_login event triggers. How can I fix that?

Thanks all!

0

First look at the observer class Magento\Checkout\Observer\LoadCustomerQuoteObserver.This observer is fire on when customer_login event and this observer does

Load data for customer quote and merge with current quote

So, it means your observe is run before this LoadCustomerQuoteObserver, that you don't get customer session at the observer.

So, in this case, I suggest to you use plugin over Magento\Checkout\Model\Session::loadCustomerQuote and use after Plugin method afterLoadCustomerQuote() that is the best way to get customer quote object during login.

<?php
namespace Stackexchange\Magento\Plugin;


class CheckoutSession
{
    public function afterLoadCustomerQuote(
        \Magento\Checkout\Model\Session $subject,
        $result
    )
    {
       $quote =  $result->getQuote();
        $contents = $quote->getAllItems();
    }
}
  • Thanks for this answer - just checking if I can make this work... – Dai J Nov 12 '18 at 10:21

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.