0

Is there an event to before_add_to_cart or add_to_cart_before? Or What can I use instead of a before add to cart event ? Thanks

  • I need to stop adding to the cart, if the price is below $ 60, can this event help me? thanks for answer Prathap Gunasekaran – Robinio Tor Apr 15 at 12:20
  • Which version of Magento 2 you are using? – Keyur Shah Apr 15 at 12:38
  • Keyur Shah Magento version is 2.2.6 – Robinio Tor Apr 15 at 12:39
2

Yes, there is an event(checkout_cart_product_add_before) before adding the product into the cart but from the Magento 2.3.X please check this link for Magento 2.3.x

But you are using Magento 2.2.6 version and in this version, this event does not exist so I would suggest you use a plugin feature of Magento.

So in your case, you want to restrict adding the product into the cart with your magic condition so go with before plugin on addProduct(..) method.

Please define plugin in your di.xml

 <type name="Magento\Checkout\Model\Cart">
        <plugin name="prevent_add_to" type="Example\Sample\Plugin\PreventAddToCart"/>
    </type>

Now define your plugin class

<?php

namespace Example\Sample\Plugin;

use Magento\Checkout\Model\Cart;

class PreventAddToCart
{

    public function beforeAddProduct(Cart $subject, $productInfo, $requestInfo = null)
    {
        if (!something) {
            throw new \Magento\Framework\Exception\LocalizedException(__("ha ha"));
        }
        return [$productInfo,$requestInfo];
    }
}

Here if (!something) { replace with your magic condition(price is less than 60)

maybe you have a question to get the product price so you can easily get it from $productInfo because is product object.

Note: I am assuming that you already know how to create a module in Magento 2

0

Try using this event controller_action_predispatch_checkout_cart_add. Hope it will be helpful for you.

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.