Question

I'm customizing one page checkout and want to add validation of new field during billing step. To make this validation I don't want to rewrite controller or model, but want to use observer controller_action_predispatch_checkout_onepage_saveBilling make all validation here and save field to Mage::getSingleton('customer/session') if it's ok or trigger an error. But I don't see any way how to add error and show it on front. I'm trying:

return array('error' => -1, 'message' => $helper->__('Your card number or zipcode are not correct.'));

Mage::app()->getResponse()->setBody(Mage::helper('core')->jsonEncode(array('error' => -1, 'message' => $helper->__('No card number was found in loyalty request'))));

I can throw exception:

 Mage::throwException('Error'); 

Than execution stops but I can't show error message.

Is there any way how to solve it?

Was it helpful?

Solution

In your observer method, you essentially need to tell the dispatcher to stop the request and not dispatch it to the controller action so that the response body you set will be sent to the browser and the controller will not do anything. Doing this is pretty simple to accomplish and can be done by setting a flag on the controller action before your observer returns:

$action = $observer->getEvent()->getControllerAction();
$action->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);

For an brief exploration of why this works, take a look at Mage_Core_Controller_Varien_Action::dispatch and note the logic surrounding the call to the action method on the controller object.

OTHER TIPS

public function observerCall($observer) 
{
    $controller = $observer->getControllerAction();
    $controller->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
    $response = array('error' => -1, 'message' => $helper->__('Error'));

    return $controller->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top