Magento – Check if product is in wishlist

blocksfull-page-cachemagento2wishlist

Magento 2.1.1, PHP 7.0.

I want to check inside product page or product list if product is in wishlist. Actually I have block which works, but only if Full Page Cache is disabled or this block in xml is marked as cacheable="false"

Is it a bug or is it by design ? Maybe I have a bug in my code?
Block:

namespace [VENDOR]\SkinHelper\Block\Catalog\Product

use \Magento\Catalog\Api\Data\ProductInterface;
use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;
use \Magento\Wishlist\Helper\Data;


class IsInWishlist extends Template
{


private $customerSession;

private $registry;

private $wishlistHelper;

public function __construct(
    Context $context,
    Data $wishlistHelper,
    array $data
)
{
    parent::__construct($context, $data);

    $this->wishlistHelper = $wishlistHelper;
}


private function getCustomerWishlistItemsCollection()
{
    $itemsCollection = $this->wishlistHelper->getWishlist()->getItemCollection();

    return $itemsCollection;
}


public function isInWishlist(ProductInterface $product)
{
    $productId = $product->getId();

    $itemsCollection = $this->getCustomerWishlistItemsCollection();
    $itemsIds = $itemsCollection->getColumnValues('product_id');

    return in_array($productId, $itemsIds);
}

It's added in catalog_category_view.xml:

<referenceBlock name="category.products.list"> <block class="[VENDOR]\SkinHelper\Block\Catalog\Product\IsInWishlist" name="name_catalog_isinwishlist" cacheable="false"/> </referenceBlock>

Part of list.phtml, where it can be called:

$IsInWishlist = $block->getChildBlock('name_catalog_isinwishlist');

<?php foreach ($_productCollection as $_product): ?> <?php $is_in_wishlist = $IsInWishlist->isInWishlist($_product) ?> <?php echo $is_in_wishlist?>

……

<php? endforeach; ?>

Best Answer

Another approach in order to retrieve wishlist or custumer related information, is to use localStorage combined with Ajax request if the localstorage is empty.

Check information in your console :

JSON.parse(localStorage.getItem('mage-cache-storage')).wishlist
JSON.parse(localStorage.getItem('mage-cache-storage')).wishlist.items[0]

enter image description here

You can based on the javascript file : vendor/magento/module-wishlist/view/frontend/web/js/view/wishlist.js

define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
], function (Component, customerData) {
    'use strict';

    return Component.extend({
        initialize: function () {
            this._super();

            this.wishlist = customerData.get('wishlist');
        }
    });
});

With this code, javascript will retrive the information with an Ajax request if the information is not stored in the local storage.

Then you can create your own Javascript component in order to manage your logic.

Related Topic