0

I need intercept the product qty before add in cart. I see the events list but don't find any observer to make this action. Any idea? Thanks.

2 Answers 2

3

please use below pluging to perform anything before addtocart

app/code/Vendor/Extension/etc/di.xml

<type name="Magento\Checkout\Model\Cart">
        <plugin name="prevent_add_to" type="Vendor\Extension\Plugin\Beforeaddtocart"/>
    </type>

app/code/Vendor/Extension/Plugin/Beforeaddtocart.php

<?php

namespace Vendor\Extension\Plugin;

use Magento\Checkout\Model\Cart;

class Beforeaddtocart
{

    public function beforeAddProduct(Cart $subject, $productInfo, $requestInfo = null)
    {
        // Code that you want to perform before addto cart
        $qty = $requestInfo['qty'];
        return [$productInfo,$requestInfo];
    }
}
4
  • Hi, how i get the qty? Thanks for your answer! Aug 4, 2020 at 13:54
  • Yes , i have updated my answer with how to get qty Aug 5, 2020 at 12:28
  • Can you upload complete module file please? Sep 13, 2020 at 11:56
  • you can just add these two files in already available module Sep 16, 2020 at 4:08
3

You can get the quantity before add to cart using observer event controller_action_predispatch_checkout_cart_add

Please use as below

app/code/Vendor/Module/etc/frontend/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="controller_action_predispatch_checkout_cart_add">
        <observer instance="Vendor\Module\Observer\Frontend\CheckQtyBeforeAddtoCart" name="check_qty_before_add_to_cart"/>
    </event>
</config>

app/code/Vendor/Module/Observer/Frontend/CheckQtyBeforeAddtoCart.php

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Vendor\Module\Observer\Frontend;

class CheckQtyBeforeAddtoCart implements \Magento\Framework\Event\ObserverInterface
{
    protected $_request;
    /**
     * RestrictWebsite constructor.
     */
    public function __construct(
        \Magento\Framework\App\RequestInterface $request
    )
    {
        $this->_request = $request;        
    }

    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {
        $postValues = $this->_request->getPostValue();
        $qty = $postValues['qty'];
    }
}

Hope this will work for you.

1
  • Can you upload complete module file please? Sep 13, 2020 at 11:56

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.