Back to Top

Preventing a product from being added to cart in magento

Updated 25 December 2017

This article is aimed towards preventing a product from being added to cart. For this we will have to call an observer.
So we can either use observer ‘checkout_cart_product_add_after‘ or ‘controller_action_predispatch_sales_order_reorder‘.

checkout_cart_product_add_after:

<checkout_cart_product_add_after>
    <observers>
        <Webkul_Module_Model_Observer>
            <type>singleton</type>
            <class>Webkul_Module_Model_Observer</class>
            <method>functionName</method>
        </Webkul_Module_Model_Observer>
    </observers>
</checkout_cart_product_add_after>

controller_action_predispatch_sales_order_reorder:

<controller_action_predispatch_sales_order_reorder>
    <observers>
        <Webkul_Module_Model_Observer>
            <type>singleton</type>
            <class>Webkul_Module_Model_Observer</class>
            <method>beforeReorder</method>
        </Webkul_Module_Model_Observer>
    </observers>
</controller_action_predispatch_sales_order_reorder>

Now after adding an observer we need to write the action which we are going to perform, i.e, preventing a product from being added to cart. We can achieve this by using either of the following 2 ways:

class Webkul_Module_Model_Observer {
    public function functionName($observer) {
        if($condition) {
            Mage::throwException(Mage::helper('module')->__('Quantity not available'));
            // OR
            Mage::getSingleton('core/session')->addNotice('Quantity not available');
            $observer->getControllerAction()->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
            Mage::app()->getResponse()->setRedirect(Mage::getUrl("checkout/cart"))->sendResponse();
        }
    }
}

In place of $condition we need to put the condition due to which the product will not be added to cart.
And that’s it.
Happy coding.

Searching for an experienced
Magento Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home