4

I want to add the product to the wishlist in magento2.

What is the way to programmatically add the product into wishlist in Magento2?

1 Answer 1

14

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();
10
  • Hello @Raphael thanks for your valuable reply. I am getting following error during compilation. Class Magento\Wishlist\Model\WishlistRepository does not exist
    – Manish
    Commented May 24, 2016 at 8:27
  • @Manish oops I reckon it should be WishlistFactory see my update Commented May 24, 2016 at 8:29
  • Hello @Raphael, by using above code I am able to add wishlist item successfully, but there is a problem in table 'wishlist_item_option' value column is null. There is no any entry for that.
    – Manish
    Commented May 24, 2016 at 9:39
  • 1
    how to do the same ...for multiple wishlists programatically in magento2
    – sangan
    Commented Apr 5, 2018 at 10:59
  • 1
    not working here - error appears -> INNER JOIN catalog_category_product_index_store0 AS cat_index ON cat_index.product_id = main_table.product_id AND cat_index.category_id = '0' AND cat_index.visibility IN (3, 2, 4) WHERE (wishlist_id = '1') AND (main_table.store_id IN('0')) at /opt/lampp/htdocs/magento2/lib/internal/Magento/Framework/DB/Statement/Pdo/Mysql.php:91)"} [] Commented Jun 18, 2020 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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