0

With my code, my product is not added (the "add to cart button" is not clickable after I clicked on in on the first time, I have to refresh)

I believe that's because my code isn't right, so I need help (to get the current product in my observer)

This is my code:

namespace Vendor\Module\Observer;    
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;

class RestrictAddToCart implements ObserverInterface
{
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $_messageManager;
    protected $registry;
    private $product;

    /**
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     */
    public function __construct(
        \Magento\Framework\Message\ManagerInterface $messageManager,
        Registry $registry
    ) {
        $this->registry = $registry;
        $this->_messageManager = $messageManager;
    }

    /**
     * add to cart event handler.
     *
     * @param \Magento\Framework\Event\Observer $observer
     *
     * @return RestrictAddToCart
     * @throws LocalizedException
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $id = $observer->getEvent()->getProduct()->geId();

        $test = false;
        if ($test == false) {
            $this->_messageManager->addErrorMessage(__($id));
            //set false if you not want to add product to cart
            $observer->getRequest()->setParam('product', false);
            return $this;
        }

        return $this;
    }
}

Using event

controller_action_predispatch_checkout_cart_add

0

you could try to set the product param to false and then set the return_url param:

  $observer->getRequest()->setParam('product', false);
  $observer->getRequest()->setParam('return_url', $this->_redirect->getRefererUrl());
  $this->_messageManager->addError(__('This product cannot be added to your cart.')); 
| improve this answer | |
  • I need to get the current product, I don't get the purpose of your code – Morgan Tartreau Oct 9 '18 at 12:43
  • 2
    you can use controller_action_predispatch_checkout_cart_add event here you can get product id . $addedItemId = $observer->getRequest()->getParam('product'); – Surendra Kumar Ahir Oct 9 '18 at 12:51
0

As you are injecting registry object, you can use the following code to get the current product object

$this->registry->registry('current_product');
| improve this answer | |

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.