TransWikia.com

Magento2 Event 'customer_register_success' or 'customer_login' for adding product to Wishlist

Magento Asked by iva on January 22, 2021

I’ve created Guest Wishlist and now I am trying to add products from cookie to a Customer Wishlist.

Problem is that if I observe ‘customer_register_success’ wishlist is not created until new customer is fully logged in.

If I observe ‘customer_login’ then problem is that I want to add products from cookie to a Wishlist ONLY if it is a new registered customer.

Not sure how to get newly registered customer wishlist?

Here is my observer ($list is array of product Ids, from a cookie named ‘guestwishlist’:

namespace VendorGuestWishlistObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoWishlistModelWishlistFactory;

class CreateAccount implements ObserverInterface
{
    /**
     * @var MagentoCatalogApiProductRepositoryInterface
     */
    protected $productRepository;

    /** @var WishlistFactory */
    protected $wishlistFactory;

    protected $_helper;

    public function __construct(
        WishlistFactory $wishlistFactory,
        VendorGuestWishlistHelperData $helper,
        MagentoCatalogApiProductRepositoryInterface $productRepository
    ) {
        $this->wishlistFactory = $wishlistFactory;
        $this->_helper = $helper;
        $this->productRepository = $productRepository;
    }

    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $customer = $observer->getEvent()->getData('customer');
        $customerId = $customer->getId();

        $list = $this->_helper->getGuestWishlist();

        if(isset($list)){

            foreach ($list as $productId){

                $product = $this->productRepository->getById($productId);

                $wishlist = $this->wishlistFactory->create()->loadByCustomerId($customerId);
                $wishlist->addNewItem($productId);
                $wishlist->save();

            }
        }
    }
}

Error that shows is ‘We can’t specify a wish list.’ when I observe event ‘customer_login’

One Answer

So, of course we can think dipper and find really native solution to your task, but lets me provide you fast work around solution.

You can just put the flag at the customer_register_success event which will say "Hello, i'm new customer at this store". You can use for example your helper to set this flag, like

$this->_helper->isNewCustomer = true;.

It's seems like good workaround, but if you need really nice solution could you please upload your extension code to the GitHub and I will try to find any better way to solve this task.

Answered by Amasty on January 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP