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; ?>
...