0

I want to limit the max products to compare to 3. I tried to create this module: https://magento.stackexchange.com/a/159543/16894

But it seems that this does not work with Magento 2.3, because I do not get any message and still can add more than 3 items.

How can I achieve this?

2
  • 1
    limiting is one thing, but reading your post, I do not know how you want the limit to be enforced? is there an error message appearing when user attempts to add 4 products to the comparator or is it another usability that I might not see obvious Jun 10, 2020 at 7:20
  • @HerveTribouilloy Thanks for the reply! Yes, it should display a error message, that there can only be 3 items displayed. This part is already in the module, if($count > self::LIMIT_TO_COMPARE_PRODUCTS) { $this->messageManager->addErrorMessage( 'You can add the compared products under 3 item(s)' );
    – JGeer
    Jun 10, 2020 at 7:21

1 Answer 1

2

I have tuned the answer that you did find faulty. The change is minor but hopefully it resolve your issue.

public function aroundExecute(
        \Magento\Catalog\Controller\Product\Compare\Add $subject,
        callable $proceed
    ) {
        $count = $this->helper->getItemCount();
        if ($count >= self::$LIMIT_TO_COMPARE_PRODUCTS) {
            $this->messageManager->addErrorMessage(
                sprintf('Only up to %s items can be added to the comparison list', self::$LIMIT_TO_COMPARE_PRODUCTS)
            );

            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect->setRefererOrBaseUrl();
        }

        return $proceed();
    }
3
  • Hello @Herve I used this method but the message gets displayed on another page or on refresh
    – Arjun
    Mar 18, 2021 at 12:58
  • Would love to help but have struggled with time lately. Will try to help again soon, thanks for your understanding Mar 18, 2021 at 21:13
  • @arjun your issue is likely due to the setup of your compare product feature in your site. This feature can be setup in various fashion. I suggest you may add a new question and describe what is your setup so that I can replicate your issue easily Apr 5, 2021 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.