I want to add the product to the wishlist in magento2.
What is the way to programmatically add the product into wishlist in Magento2?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityTo 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();
WishlistFactory
see my update
May 24, 2016 at 8:29
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)"} []
Jun 18, 2020 at 9:24