Magento – Check Billing/Shipping Address in Onepage Checkout from Observer

ajaxevent-observermagento-1.9onepage-checkout

I'm trying to check billing / shipping address and break onepage checkout with an error, if the addresses do not meet some conditions of the quote (e.g. some products should only be shipped to the country XY).

Approach

Make use of the event controller_action_postdispatch_checkout_onepage_saveBilling and controller_action_postdispatch_checkout_onepage_saveShipping, the observer code is something like:

    public function checkBillingAddress(Varien_Event_Observer $observer) {

    /** @var $quote Mage_Sales_Model_Quote */
    $quote = Mage::getSingleton('checkout/session')->getQuote();

    $special_products = 0;
    foreach($items as $item) {
        $sku = $item->getData('sku');
        $isGuaranteeredProduct = $helper->isGuaranteeredProduct($sku);
        $special_products++;
    }
    if($special_products > 0) {
        Mage::getSingleton('core/session')->addError(Mage::helper('core')->__('Orders with special products can only be shipped to XY!'));
    }
}

Problem

How can I return the error via AJAX and break checkout in a right way?

Thank you for your ideas.

Best Answer

You could try Mage::throwException('An error message') under the session error message. Or you can force a redirect in the section where you set the error. I had done this for another question and it seemed to work as expected inside the event observer:

    $error_message = 'Sorry, we are unable to continue, you have items in your cart that need to be delivered within Dehli';
    Mage::getSingleton('core/session')->addError($error_message);
    Mage::throwException($error_message);