0

How to remove product from wishlist using customer id and product id programmatically? I searched a lot about it, But the results are remove wishlist item using item id only. So is there any way to remove wish list item using customer id and product id only?

code -

<?php

/**
 * A Magento 2 module named Hp/Wishlist
 *  
 */

namespace Hp\Wishlist\Model;

use Hp\Wishlist\Api\WishlistManagementInterface;
use Magento\Wishlist\Controller\WishlistProvider;
use Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory;
use Magento\Wishlist\Model\WishlistFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Helper\ImageFactory as ProductImageHelper;
use Magento\Store\Model\App\Emulation as AppEmulation;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Wishlist\Model\Item;
use Magento\Wishlist\Controller\WishlistProviderInterface;



/**
 * Defines the implementaiton class of the WishlistManagementInterface
 */
class WishlistManagement implements WishlistManagementInterface
{

      /**
     * @var WishlistProviderInterface
     */
    protected $wishlistProvider;
    private $wishlist;
    /**
     * @var CollectionFactory
     */
    protected $_wishlistCollectionFactory;
    /**
     * @var CustomerRegistry
     */
    protected $_wishlistFactory;
    /**
     *@var \Magento\Catalog\Model\Product
     */
    private $_objectManager;

    protected $_productload;
    /**
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storemanagerinterface;
    protected $customerRegistry;

    public function __construct(
        CustomerRegistry $customerRegistry,
        \Magento\Framework\ObjectManagerInterface $objectmanager,
        WishlistProviderInterface $wishlistProvider,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        \Magento\Store\Model\StoreManagerInterface $storemanagerinterface,
        \Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory $_wishlistCollectionFactory,
        \Magento\Wishlist\Model\WishlistFactory $wishlistFactory,
        \Magento\Wishlist\Model\Wishlist $wishlist

    ) {
        $this->_objectManager = $objectmanager;
        $this->wishlistProvider = $wishlistProvider;
        $this->wishlist                   = $wishlist;
        $this->_productloader             = $_productloader;
        $this->_wishlistFactory           = $wishlistFactory;
        $this->_wishlistCollectionFactory = $_wishlistCollectionFactory;
        $this->storemanagerinterface      = $storemanagerinterface;
        $this->customerRegistry = $customerRegistry;
    }

    /**
     * Get customer's name by Customer ID and return greeting message.
     *
     * @api
     * @param int $customerId
     * @return \Magento\Customer\Api\Data\CustomerInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException If customer with the specified ID does not exist.
     * @throws \Magento\Framework\Exception\LocalizedException
     */

    public function addWishlistForCustomer($customerId, $productId)
    {

        if ($productId == null) {
            throw new LocalizedException(__('Invalid product, Please select a valid product'));
        }
        try {
            $product = $this->_productloader->create()->load($productId);
        } catch (NoSuchEntityException $e) {
            $product = null;
        }
        try {
            $wishlist = $this->_wishlistFactory->create();
            $wishlist->loadByCustomerId($customerId, true);
            $wishlist->addNewItem($productId);
            $wishlist->save();
            return 'Product with sku - ' . $product->getSku() . ' is added to wishlist';
        } catch (NoSuchEntityException $e) {
        }
        return true;
    }

    public function getWishlistForCustomer($customerId)
    {
        if (empty($customerId) || !isset($customerId) || $customerId == "") {
            throw new InputException(__('Id required'));
        } else {

            $collection =
                $this->_wishlistCollectionFactory->create()
                ->addCustomerIdFilter($customerId)->getData();
            $wishlistData = [];
            foreach ($collection as $item) {
                $productInfo = $this->_productloader->create()->load($item['product_id']);

                $data = [
                    "wishlist_item_id" => $item['wishlist_item_id'],
                    "wishlist_id"      => $item['wishlist_id'],
                    "product_id"       => $item['product_id'],
                    "store_id"         => $item['store_id'],
                    "added_at"         => $item['added_at'],
                    "description"      => $item['description'],
                    "qty"              => round($item['qty']),
                    "product"          => $productInfo,
                ];

                $wishlistData[] = $data;
            }
            return $wishlistData;
        }
    }

    public function removeWishlistForCustomer($customerId, $productId)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $item = $this->_objectManager->create(Item::class)->load($productId);
        $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId());
        $item->delete();
            $wishlist->save();

        return 'is removed from wishlist'; 
    }
}

error

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')) {"exception":"[object] (Exception(code: 42): Report ID: webapi-5ef4ac78b3d65; Message: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'm233.catalog_category_product_index_store0' doesn't exist, query was: SELECT `main_table`.* FROM `wishlist_item` AS `main_table`
0

Try this :-

protected $wishlist;

public function __construct(
    \Magento\Wishlist\Model\Wishlist $wishlist
) {
    $this->wishlist = $wishlist;
}

public function execute()
{
    $customerId = 1;
    $productId = 6;
    $wish = $this->wishlist->loadByCustomerId($customerId);
    $items = $wish->getItemCollection();

    /** @var \Magento\Wishlist\Model\Item $item */
    foreach ($items as $item) {
        if ($item->getProductId() == $productId) {
            $item->delete();
            $wish->save();
        }
    }
}
  • let me check this – devmage Jun 23 '20 at 6:46
  • its not working – devmage Jun 25 '20 at 12:27
  • any error ????? – Rk Rathod Jun 25 '20 at 13:13
  • Yes sir , error posted in question – devmage Jun 25 '20 at 13:58
  • please take a look at the updated question – devmage Jun 25 '20 at 13:59

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.