1

In Magento 2: I have created the event observer:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_add">
        <observer name="orange_conditions" instance="Namespace\Name\Observer\RestrictAddToCart" />
    </event>
</config>

In the observer execute method I would like to do the following:

Access the information (object) from the product I have clicked on.

To keep it simple: the SKU. Later on I would like to have access to some other parameters. But first things first ...

Below code is a start, but it is not working. (found this in other questions)

public function execute(\Magento\Framework\Event\Observer $observer) {
        /** @var \Magento\Catalog\Model\Product $product */
        $product = $observer->getEvent()->getDataByKey('product');

        /** @var \Magento\Quote\Model\Quote\Item $item */
        $item = $this->_checkoutSession->getQuote()->getItemByProduct($product);

        $itemId = $item->getId();

        $this->_messageManager->addError($item);
        //set false if you not want to add product to cart
        $observer->getRequest()->setParam('product', false);
}
1

Try following way:

<?php
namespace SR\MagentoCommunity\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Message\ManagerInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Store\Model\StoreManagerInterface;

class RestrictAddToCart implements ObserverInterface
{
    /**
     * @var ProductRepository
     */
    private $productRepository;

    /**
     * @var ManagerInterface
     */
    private $messageManager;

    /**
     * @var CheckoutSession
     */
    private $checkoutSession;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * RestrictAddToCart constructor.
     *
     * @param ProductRepository $productRepository
     * @param ManagerInterface $messageManager
     * @param CheckoutSession $checkoutSession
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        ProductRepository $productRepository,
        ManagerInterface $messageManager,
        CheckoutSession $checkoutSession,
        StoreManagerInterface $storeManager
    ) {
        $this->productRepository = $productRepository;
        $this->messageManager = $messageManager;
        $this->checkoutSession = $checkoutSession;
        $this->storeManager = $storeManager;
    }

    public function execute(EventObserver $observer)
    {
        try {
            $productId = $observer->getRequest()->getParam('product');
            $storeId = $this->storeManager->getStore()->getId();
            /** @var \Magento\Catalog\Model\Product $product */
            $product = $this->productRepository->getById($productId, false, $storeId);
            /** @var \Magento\Quote\Model\Quote\Item $item */
            $item = $this->checkoutSession->getQuote()->getItemByProduct($product);
            if ($item) {
                $itemId = $item->getId();
                $this->messageManager->addErrorMessage($item->getName());
            }

        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        }

        //set false if you not want to add product to cart
        $observer->getRequest()->setParam('product', false);
    }
}
  • Why are you using $item = $this->checkoutSession->getQuote()->getItemByProduct($product);? This event is fired before adding it into the cart, so that could declare why $item is empty not? Or am I wrong? Using $product->getSku() is working ...? – user3086053 Mar 2 at 18:59
0

I think you have to get the product in your observer like this:

$product = $observer->getRequest()->getParam('product');
  • Changing this, and getting the $itemId is returning error ... PHP Fatal error: Uncaught Error: Call to a member function getId() on boolean – user3086053 Mar 1 at 17:18
0

I have just tried and found out the below would sort you out:

$productId = $observer->getControllerAction()->getRequest()->getParam('product');

Of course I allow myself to reuse part of the answer below and hook it to the line I advise you to use:

public function execute(EventObserver $observer)
{
    try {
       $productId = $observer->getControllerAction()->getRequest()->getParam('product');
       $storeId = $this->storeManager->getStore()->getId();
       /** @var \Magento\Catalog\Model\Product $product */
       $product = $this->productRepository->getById($productId, false, $storeId);
       /** @var \Magento\Quote\Model\Quote\Item $item */
       $item = $this->checkoutSession->getQuote()->getItemByProduct($product);
       if ($item) {
            $itemId = $item->getId();
            $this->messageManager->addErrorMessage($item->getName());
       }
   }
    ..

good luck

  • why are you using the 'getControllerAction()'? @sohal-rana rule is working too? – user3086053 Mar 2 at 18:56
  • If the below works, please discard my answer as it is clearly more complicated. My idea was that the dispatch process had a controller from which you get the request. I am surprised to hear the request is available directly at this part of the system – Herve Tribouilloy Mar 2 at 19:26

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.