Looking for a better way to add and remove the product on click of same icon.

If a product is already added to the compare collection then on next click of that icon, It should remove the product from compare collection.

protected  $_productloader;
protected $_compareItemFactory;
protected $_catalogProductCompareList;

public function __construct(
    \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory,
    \Magento\Catalog\Model\Product\Compare\ListCompare $catalogProductCompareList,
    \Magento\Catalog\Model\ProductFactory $productloader
) {
    $this->_productloader = $productloader;
    $this->_compareItemFactory = $compareItemFactory;
    $this->_catalogProductCompareList = $catalogProductCompareList;

public function execute()
    $productId = (int)$this->getRequest()->getParam('product');
  • For this need to create new file or change in existing.please show path. – Ketan Borada Mar 8 '18 at 4:59
  • @KetanKpBorada create new is good but you can modify the existing as your requirement. – Qaisar Satti Mar 8 '18 at 5:00
  • please show full path with file name. – Ketan Borada Mar 8 '18 at 5:14
  • @KetanKpBorada kindly add your module ad redirect it on your controllers don't try to edit the core file. – Qaisar Satti Mar 8 '18 at 5:16
  • 1
    @ToanNguyen it was write code for test but thanks for notice and 22k not mean i am best. – Qaisar Satti Mar 9 '18 at 6:56

You can remove product from compare collection using below code:

<a href="#" class="action tocompare" title="<?php echo $block->escapeHtml(__('Remove Compare')); ?>"
           aria-label="<?php echo $block->escapeHtml(__('Remove Compare')); ?>"
         data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataRemove($_product); ?>'
      <span><?php /* @escapeNotVerified */ echo __('Remove Compare') ?></span>
  • where is added this code please specify on file and path – Rv Singh Aug 30 '19 at 11:45

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.