How to know if customer already have product in wishlist at product view page in magento 2 - Magesan

How to know if customer already have product in wishlist at product view page in magento 2

How to know if customer already have product in wishlist at product view page in magento 2

By default magento isn’t provide you the facility to check if product already in wishlist or not.

But if you want rich feature to your site. This is one of the feature you can use.

Here, we are going to add active class based on product.

Before we proceed, Make sure you have a bit knowledge of how to create a module in magento 2

We are going to implement this functionality in the module named Magesan_Wishlist

So, lets start

Create a module file registration.php at app/code/Magesan/Wishlist/registration.php

registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magesan_Wishlist',
    __DIR__
);

Create a module file module.xml at app/code/Magesan/Wishlist/etc/module.xml

module.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Elightwalk_Wishlist" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Wishlist" />
        </sequence>
    </module>
</config>

We need to create preferance for overriding the default wishlist block

Create a di.xml file at app/code/Magesan/Wishlist/etc/frontend/di.xml

di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Wishlist\Block\Catalog\Product\View\AddTo\Wishlist" type="Magesan\Wishlist\Block\Catalog\Product\View\AddTo\Wishlist" />
</config>

Create a Wishlist.php class at app/code/Magesan/Wishlist/Block/Catalog/Product/View/AddTo/Wishlist.php

Wishlist.php

<?php

namespace Magesan\Wishlist\Block\Catalog\Product\View\AddTo;

use Magento\Wishlist\Block\Catalog\Product\View\AddTo\Wishlist as MagentoWishlist;
use Magento\Catalog\Block\Product\Context;
use Magento\Framework\Url\EncoderInterface;
use Magento\Framework\Json\EncoderInterface as JsonEncoder;
use Magento\Framework\Stdlib\StringUtils;
use Magento\Catalog\Helper\Product;
use Magento\Catalog\Model\ProductTypes\ConfigInterface;
use Magento\Framework\Locale\FormatInterface;
use Magento\Customer\Model\Session;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Customer\Model\SessionFactory;
use Magento\Wishlist\Model\WishlistFactory;
use Psr\Log\LoggerInterface;

class Wishlist extends MagentoWishlist
{
    /**
     * @var WishlistFactory
     */
    protected $_wishlistFactory;

    /**
     * @var SessionFactory
     */
    protected $_customerSession;

    /**
     * @var LoggerInterface
     */
    protected $_logger;

    /**
     * __construct
     *
     * @param Context $context
     * @param EncoderInterface $urlEncoder
     * @param JsonEncoder $jsonEncoder
     * @param StringUtils $string
     * @param Product $productHelper
     * @param ConfigInterface $productTypeConfig
     * @param FormatInterface $localeFormat
     * @param Session $session
     * @param ProductRepositoryInterface $productRepository
     * @param PriceCurrencyInterface $priceCurrency
     * @param WishlistFactory $wishlistFactory
     * @param SessionFactory $customerSession
     * @param LoggerInterface $logger
     * @param array $data
     */
    public function __construct(
        Context $context,
        EncoderInterface $urlEncoder,
        JsonEncoder $jsonEncoder,
        StringUtils $string,
        Product $productHelper,
        ConfigInterface $productTypeConfig,
        FormatInterface $localeFormat,
        Session $session,
        ProductRepositoryInterface $productRepository,
        PriceCurrencyInterface $priceCurrency,
        WishlistFactory $wishlistFactory,
        SessionFactory $customerSession,
        LoggerInterface $logger,
        array $data = []
    ) {
        parent::__construct(
            $context,
            $urlEncoder,
            $jsonEncoder,
            $string,
            $productHelper,
            $productTypeConfig,
            $localeFormat,
            $session,
            $productRepository,
            $priceCurrency,
            $data
        );
        $this->_wishlistFactory = $wishlistFactory;
        $this->_customerSession = $customerSession;
        $this->_logger          = $logger;
    }

    /**
     * GetCustomerId
     *
     * @return integer
     */
    public function getCustomerId(): int
    {
        $customerId = 0;
        try {
            $customer = $this->_customerSession->create()->getCustomer();
            if ($customer && $customer->getId()) {
                $customerId = (int) $customer->getId();
            }
        } catch (\Exception $exception) {
            $this->_logger->error($exception->getMessage());
        } catch (\Error $error) {
            $this->_logger->error($error->getMessage());
        }

        return $customerId;
    }

    /**
     * IsProductInWishlist
     *
     * @return boolean
     */
    public function isProductInWishlist(): bool
    {
        $isInWishlist = false;
        try {
            $customerId = $this->getCustomerId();
            if ($customerId) {
                $wishlist = $this->_wishlistFactory->create()->loadByCustomerId($customerId, true);
                $product  = $this->getProduct();

                if ($wishlist->getId() && $wishlist->getItemsCount() > 0) {
                    foreach ($wishlist->getItemCollection() as $item) {
                        if ($item->getProductId() == $product->getId()) {
                            $isInWishlist = true;
                            break;
                        }
                    }
                }
            }
        } catch (\Exception $exception) {
            $this->_logger->error($exception->getMessage());
        } catch (\Error $error) {
            $this->_logger->error($error->getMessage());
        }

        return $isInWishlist;
    }
}

We are good to go now.

Now we just need to override the wishlist.phtml file to our custom theme.

app/design/frontend/Custom/Theme/Magento_Wishlist/templates/catalog/product/view/addto/wishlist.phtml

wishlist.phtml

<?php

/** @var \Magesan\Wishlist\Block\Catalog\Product\View\AddTo\Wishlist $block */
?>
<?php if ($block->isWishListAllowed()) : ?>
    <a href="#" class="action towishlist <?php if ($block->isInWishlist()) echo 'active'; ?>" data-post='<?= /* @noEscape */ $block->getWishlistParams() ?>' data-action="add-to-wishlist">
        <span><?= $block->escapeHtml(__('Add to Wish List')) ?></span>
    </a>
<?php endif; ?>
<script type="text/x-magento-init">
    {
        "body": {
            "addToWishlist": <?= /* @noEscape */ $block->getWishlistOptionsJson() ?>
        }
    }
</script>

It will add the active class if the product is in wishlist. And based on active class we make make the wishlist button filled or something animatic if the product is in wishlist via active class.

Happy coding…

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>