1

anyone having an idea how to compare only that category which is having the same parent.

for example, a customer can compare Samsung washing machine with LG washing machine but if customer wants to compare Microwave or Oven with washing machine then it will not allow a customer to compare those products.

i tried to override default catalog compare controller.

<?php
namespace Custom\Compare\Controller\Product\Compare;

class CustomAdd extends \Magento\Catalog\Controller\Product\Compare
{

    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        if (!$this->_formKeyValidator->validate($this->getRequest())) {
            return $resultRedirect->setRefererUrl();
        }

        $productId = (int)$this->getRequest()->getParam('product');
        if ($productId && ($this->_customerVisitor->getId() || $this->_customerSession->isLoggedIn())) {
            $storeId = $this->_storeManager->getStore()->getId();
            try {
                $product = $this->productRepository->getById($productId, false, $storeId);
            } catch (NoSuchEntityException $e) {
                $product = null;
            }

            if ($product) {
                $this->_catalogProductCompareList->addProduct($product);
                $productName = $this->_objectManager->get(
                    \Magento\Framework\Escaper::class
                )->escapeHtml($product->getName());
                $this->messageManager->addSuccess(__('You added product %1 to the comparison list.', $productName));
                $this->_eventManager->dispatch('catalog_product_compare_add_product', ['product' => $product]);
            }

            $this->_objectManager->get(\Magento\Catalog\Helper\Product\Compare::class)->calculate();
        }
        return $resultRedirect->setRefererOrBaseUrl();
    }
}
2
  • So, this attempt to override is unsuccessful and you still need to be able to compare cross category products? – Marjan Sep 19 '18 at 17:30
  • @Marjan override attempt successful and found solution for question. Will add solution here so it can be helpful – sandip Sep 21 '18 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.