0

when i am trying to add product multiple times in wishlist i am getting below message :

Product A has been added to your Wish List. Click here to continue shopping.

instead, it should be

Product A is already in your Wish List. Click here to continue shopping.

Based on solution I added below code in Add.php as my magento version it 2.1 but it gives below error

Uncaught TypeError: Argument 5 passed to Vendor\Magento\Controller\Index\Add::__construct() must be an instance of Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory, instance of Magento\Framework\Data\Form\FormKey\Validator given, called

<?php

namespace Vendor\Magento\Controller\Index;    
use Magento\Catalog\Api\ProductRepositoryInterface;
    use Magento\Framework\App\Action;
    use Magento\Framework\Controller\ResultFactory;
    use Magento\Framework\Data\Form\FormKey\Validator;
    use Magento\Framework\Exception\NoSuchEntityException;
    use Magento\Framework\Exception\NotFoundException;

    class Add extends \Magento\Wishlist\Controller\AbstractIndex
{
    protected $wishlistProvider;
    protected $_customerSession;
    protected $productRepository;
    protected $formKeyValidator;
    protected $wishItemscollection;

    public function __construct(
        Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider,
        ProductRepositoryInterface $productRepository,
        \Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory $wishItemscollection,
        Validator $formKeyValidator
    ) {
        $this->_customerSession = $customerSession;
        $this->wishlistProvider = $wishlistProvider;
        $this->productRepository = $productRepository;
        $this->wishItemscollection = $wishItemscollection;
        $this->formKeyValidator = $formKeyValidator;
        parent::__construct($context);
    }

    /**
     * Adding new item
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     * @throws NotFoundException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$this->formKeyValidator->validate($this->getRequest())) {
            return $resultRedirect->setPath('*/');
        }

        $wishlist = $this->wishlistProvider->getWishlist();
        if (!$wishlist) {
            throw new NotFoundException(__('Page not found.'));
        }

        $session = $this->_customerSession;

        $requestParams = $this->getRequest()->getParams();

        if ($session->getBeforeWishlistRequest()) {
            $requestParams = $session->getBeforeWishlistRequest();
            $session->unsBeforeWishlistRequest();
        }

        $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null;
        if (!$productId) {
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

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

        if (!$product || !$product->isVisibleInCatalog()) {
            $this->messageManager->addErrorMessage(__('We can\'t specify a product.'));
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

        try {
            $buyRequest = new \Magento\Framework\DataObject($requestParams);

            // your need to check here if product is already added or not
            /* your logic is here  */

            $store_id = $this->_customerSession->getCustomer()->getStoreId();
            $wishlist_id = $wishlist->getId();

            // add to wishlist items table
            $wishlist_itemCollection = $this->wishItemscollection->create();
            $wishlist_itemCollection->addFieldToFilter('product_id', $productId);
            $wishlist_itemCollection->addFieldToFilter('store_id', $store_id);
            $wishlist_itemCollection->addFieldToFilter('wishlist_id', $wishlist_id);
            //print_r($wishlist_itemCollection->getData());
            $wishlist_count = count($wishlist_itemCollection->getData());
            if ($wishlist_count == 0) {
                // new product item come
                $result = $wishlist->addNewItem($product, $buyRequest); // this line add product to wishlist
                if (is_string($result)) {
                    throw new \Magento\Framework\Exception\LocalizedException(__($result));
                }
                if ($wishlist->isObjectNew()) {
                    $wishlist->save();
                }
                $this->_eventManager->dispatch(
                    'wishlist_add_product',
                    ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]
                );

                $referer = $session->getBeforeWishlistUrl();
                if ($referer) {
                    $session->setBeforeWishlistUrl(null);
                } else {
                    $referer = $this->_redirect->getRefererUrl();
                }

                $this->_objectManager->get(\Magento\Wishlist\Helper\Data::class)->calculate();

                // this message you change or call your custom message
                $this->messageManager->addComplexSuccessMessage(
                    'addProductSuccessMessage',
                    [
                        'product_name' => $product->getName(),
                        'referer' => $referer,
                    ]
                );

            } else{
                /// add your cusom message for already wishlist product 
                $this->messageManager->addErrorMessage(__($product->getName() . ' has been already added to your Wish List. '));
            }
            // phpcs:disable Magento2.Exceptions.ThrowCatch
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addErrorMessage(
                __('We can\'t add the item to Wish List right now: %1.', $e->getMessage())
            );
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage(
                $e,
                __('We can\'t add the item to Wish List right now.')
            );
        }

        $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
        return $resultRedirect;
    }
}
1

/vendor/magento/module-wishlist/Controller/Index/Add.php

from this line 137

        $this->messageManager->addComplexSuccessMessage(
            'addProductSuccessMessage',
            [
                'product_name' => $product->getName(),
                'referer' => $referer,
            ]
        );

You need to override wishlist add Controller and modify it according to your requirements.

app/code/VendoreName/ModuleName/etc

di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <!-- for override add wishlist product  -->
    <preference for="Magento\Wishlist\Controller\Index\Add" type="VendoreName\ModuleName\Controller\Index\Add" />

</config>

app\code\VendoreName\ModuleName\Controller\Index

Add.php

<?php

namespace VendoreName\ModuleName\Controller\Index;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\NotFoundException;

class Add extends \Magento\Wishlist\Controller\AbstractIndex implements HttpPostActionInterface
{
    protected $wishlistProvider;
    protected $_customerSession;
    protected $productRepository;
    protected $formKeyValidator;
    protected $wishItemscollection;

    public function __construct(
        Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Wishlist\Controller\WishlistProviderInterface $wishlistProvider,
        ProductRepositoryInterface $productRepository,
        \Magento\Wishlist\Model\ResourceModel\Item\CollectionFactory $wishItemscollection,
        Validator $formKeyValidator
    ) {
        $this->_customerSession = $customerSession;
        $this->wishlistProvider = $wishlistProvider;
        $this->productRepository = $productRepository;
        $this->wishItemscollection = $wishItemscollection;
        $this->formKeyValidator = $formKeyValidator;
        parent::__construct($context);
    }

    /**
     * Adding new item
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     * @throws NotFoundException
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
     */
    public function execute()
    {
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        if (!$this->formKeyValidator->validate($this->getRequest())) {
            return $resultRedirect->setPath('*/');
        }

        $wishlist = $this->wishlistProvider->getWishlist();
        if (!$wishlist) {
            throw new NotFoundException(__('Page not found.'));
        }

        $session = $this->_customerSession;

        $requestParams = $this->getRequest()->getParams();

        if ($session->getBeforeWishlistRequest()) {
            $requestParams = $session->getBeforeWishlistRequest();
            $session->unsBeforeWishlistRequest();
        }

        $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null;
        if (!$productId) {
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

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

        if (!$product || !$product->isVisibleInCatalog()) {
            $this->messageManager->addErrorMessage(__('We can\'t specify a product.'));
            $resultRedirect->setPath('*/');
            return $resultRedirect;
        }

        try {
            $buyRequest = new \Magento\Framework\DataObject($requestParams);

            // your need to check here if product is already added or not
            /* your logic is here  */

            $store_id = $this->_customerSession->getCustomer()->getStoreId();
            $wishlist_id = $wishlist->getId();

            // add to wishlist items table
            $wishlist_itemCollection = $this->wishItemscollection->create();
            $wishlist_itemCollection->addFieldToFilter('product_id', $productId);
            $wishlist_itemCollection->addFieldToFilter('store_id', $store_id);
            $wishlist_itemCollection->addFieldToFilter('wishlist_id', $wishlist_id);
            //print_r($wishlist_itemCollection->getData());
            $wishlist_count = count($wishlist_itemCollection->getData());
            if ($wishlist_count == 0) {
                // new product item come
                $result = $wishlist->addNewItem($product, $buyRequest); // this line add product to wishlist
                if (is_string($result)) {
                    throw new \Magento\Framework\Exception\LocalizedException(__($result));
                }
                if ($wishlist->isObjectNew()) {
                    $wishlist->save();
                }
                $this->_eventManager->dispatch(
                    'wishlist_add_product',
                    ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]
                );

                $referer = $session->getBeforeWishlistUrl();
                if ($referer) {
                    $session->setBeforeWishlistUrl(null);
                } else {
                    $referer = $this->_redirect->getRefererUrl();
                }

                $this->_objectManager->get(\Magento\Wishlist\Helper\Data::class)->calculate();

                // this message you change or call your custom message
                $this->messageManager->addComplexSuccessMessage(
                    'addProductSuccessMessage',
                    [
                        'product_name' => $product->getName(),
                        'referer' => $referer,
                    ]
                );

            } else{
                /// add your cusom message for already wishlist product 
                $this->messageManager->addErrorMessage(__($product->getName() . ' has been already added to your Wish List. '));
            }
            // phpcs:disable Magento2.Exceptions.ThrowCatch
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addErrorMessage(
                __('We can\'t add the item to Wish List right now: %1.', $e->getMessage())
            );
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage(
                $e,
                __('We can\'t add the item to Wish List right now.')
            );
        }

        $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]);
        return $resultRedirect;
    }
}

Update

please comment this line

if (!$this->formKeyValidator->validate($this->getRequest())) {
    return $resultRedirect->setPath('*/');
}

and Please check file path

<magento root>\vendore\magento\module-wishlist\Model\ResourceModel\Item\Collection.php 

above file is exist or not if yes then please run below command

php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:f

and please clean your browser cache by pressing Ctrl + Shift + Delete key

| improve this answer | |
  • let me inform it's helps you ? – Msquare Mar 18 at 8:57
  • still getting same message i want if product in compare it show show message like "product already in wishlist list" – user1799722 Mar 23 at 16:47
  • please check my updated answer. i added logic. let me inform it' work for you or not. – Msquare Mar 24 at 5:12
  • update code but ti gives some error – user1799722 Mar 24 at 7:31
  • please show your error. have you run magento command set:up and cache:clean before code check ? – Msquare Mar 24 at 7:31
0

override vendor/magento/module-wishlist/i18n/en_US.csv to your theme in Magento_Wishlist and find "%1 has been added to your Wish List." and change the message. Whenever override any i18n/en_US.csv then compulsory to deploy.

sudo rm -rf var/*
sudo rm -rf pub/static/frontend/*

sudo php bin/magento setup:static-content:deploy -f
sudo php bin/magento ca:cl
sudo php bin/magento ca:fl
sudo chmod -R 777 /var/www/html/(project name)/

if above solution is not working then override /vendor/magento/module-wishlist/view/frontend/templates/messages/addProductSuccessMessage.phtml and change message.

I hope this will help you.

| improve this answer | |

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.