EOB
EOB

Reputation: 3085

Magento: stopping the add to cart process in an observer?

I am observing an event which is fired when a product is added to the cart. This is the tutorial I used for it: http://inchoo.net/ecommerce/magento/dispatching-before-and-after-events-to-magento-core-actions/

Now under some conditions I want to stop the process of adding the product to the cart. I tried throwing an exception, but this gives me the There has been an error processing your request error message. Checking the report that is created by Magento does not tell me anything. How else could I stop the adding process?

This is my code:

public function hookToAddToCartBefore($observer) {
    ...
    if(somecondition) {
         Mage::throwException('some message');
    }
}

Upvotes: 0

Views: 1738

Answers (1)

Tyler
Tyler

Reputation: 175

Features:

  • Clear error message after
  • Skips all "add to cart" code
  • Redirect to the page of your choice after

After trying every imaginable thing out there to attempt to gracefully abort an "add to cart", I managed to combine pieces and discovered the flag FLAG_NO_DISPATCH by stepping through the source. Other attempts to change params or set redirect would be overwritten by some code further in the "add to cart" process.

    Mage::app()->getResponse()->setRedirect($store_product->getProductUrl());
    Mage::getSingleton('checkout/session')->addError(Mage::helper('checkout')->__('Sorry, the price of this product has been updated. Please, add to cart after reviewing the updated price.'));
    $observer->getControllerAction()->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);  

Instead of error, you can have a notice:

Mage::getSingleton('core/session')->addNotice('Sorry, this product is currently not available...');

Upvotes: 1

Related Questions