0

When we create a new product at the same time I want that product to add into wishlist. How can this be done in Magento 2? Can somebody help me?

3
  • It is not possible without customer login. Have your particular customer data id or email?
    – Abdul
    Apr 12, 2018 at 12:53
  • Yes. But if having customer data and email how it is possible? Apr 12, 2018 at 12:59
  • Yes, if you have customer data then it is possible
    – Abdul
    Apr 12, 2018 at 13:08

2 Answers 2

0

To do so, you will first have to inject the following in your constructor:

Magento\Wishlist\Model\WishlistFactory
Magento\Catalog\Api\ProductRepositoryInterface

So update your class constructor like this:

protected $_wishlistRepository;

protected $_productRepository;

public function __construct(
    ...
    \Magento\Wishlist\Model\WishlistFactory $wishlistRepository,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->_wishlistRepository= $wishlistRepository;
    $this->_productRepository = $productRepository;
    ...
}

Then in you can do the following, please note your need both the customer id and the product id to add a product to the wishlist:

try {
    $product = $this->_productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
    $product = null;
}

$wishlist = $this->_wishlistRepository->create()->loadByCustomerId($customerId, true);

$wishlist->addNewItem($product);
$wishlist->save();
1
0

This will work for you :

<?php

namespace Company\Module\Controller\Index;

    class Index extends \Magento\Contact\Controller\Index\Post {

        protected $_wishlistObj;
        protected $_productObj;

        public function __construct(\Magento\Wishlist\Model\WishlistFactory $wishlistObj, \Magento\Catalog\Api\ProductRepositoryInterface $productObj) {
            $this->_wishlistObj = $wishlistObj;
            $this->_productObj = $productObj;
        }

        public function execute() {
                $data=$this->getRequest()->getPost();
                $product = $this->_productObj->getById($data['product_id']);

            $wishlist = $this->_wishlistObj->create()->loadByCustomerId($data['customer_id'], true);

            $wishlist->addNewItem($product);
            $wishlist->save();
        }

    }

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