0

Events do not work when I go to the product page.

events.xml

<?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="adding_to_cart_before">
        <observer name="attributesProduct" instance="Ronis\SameDayDelivery\Observer\DayDelivery" />
    </event>
</config>

DayDelivery.php

<?php

namespace Ronis\SameDayDelivery\Observer;

use Magento\Framework\Event\ObserverInterface;

class DayDelivery implements ObserverInterface
{
    protected $resultPageFactory;

    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $_cart;

    /**
     * [__construct description]
     * @param \Magento\Framework\App\Action\Context $context [description]
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory [description]
     * @param \Magento\Checkout\Model\Cart $cart [description]
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Checkout\Model\Cart $cart
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->_cart = $cart;
        parent::__construct($context);
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/daydelivery.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);

        $productInfo = $this->_cart->getQuote()->getItemsCollection();
        $logger->info('-------------------------');
        foreach ($productInfo as $item){
            $item->getProductId();
            $logger->info($item->getProductId());
            if($item->getProductId() == '1')
            {
                echo "Item available in cart";
            }
            else
            {
                echo "Item not available in cart";
            }
        }
    }
}
2

Try this,

You should use this event controller_action_predispatch_catalog_product_view instead of adding_to_cart_before

but the problem is, it will trigger only on first time when you visit the product page, since it is cacheable page. You may try disable cacheable="false" to any of the block from product page and check then it will trigger all the time you visit.

NOTE : It's not recommended to disable cache on product page, so try using plugin to do that.

Hope this information helps.

  • and how can I now transfer these id's to the js template so that, depending on this ids, I showed a popup on the product page – Рома Лытарь Apr 8 at 14:08

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.