customer_address_save_before event and normalizing customer input with error notices

magento.stackexchange https://magento.stackexchange.com/questions/13144

  •  16-10-2019
  •  | 
  •  

Question

I have enabled customer address entry during account creation via flag in local.xml:

<customer_account_create>
    <reference name="customer_form_register">
        <action method="setShowAddressFields">
            <value>true</value>
        </action>
    </reference>
</customer_account_create>

I also have an observer being called before address save (and depends on Mage_Customer during module load):

<customer_address_save_before>
    <observers>
        <mymodule>
            <class>mymodules/observer</class>
            <method>normalizeAddress</method>
        </mymodule>
    </observers>
</customer_address_save_before>

My observer intends to swap data in the event's object, basically:

$helper = Mage::helper('mymodule');
$observer->getCustomerAddress()->setRegion($helper->normalize($observer->getCustomerAddress()->getRegion()));
$observer->getCustomerAddress()->setCity($helper->normalize($observer->getCustomerAddress()->getCity()));

This is wonderful. I love my module. Except, now there is the problem of error handling. My helper's normalize() method receives a response where an error number and message might be included in the object along with original values, otherwise it contains the normalized values.

If there is an error message at this point, I'd like to stop and redirect the user back to the form page and include the response's error message as a error notice to the user (and abandon saving the customer):

if ($response->hasErrorMessage()) {
    Mage::getSingleton('customer/session')->addError($response->getErrorMessage());
    Mage::app()->getResponse()->setRedirect(Mage::getUrl('customer/account/create'));
}

However, trying this fails (customer is saved with unnormalized data) as what I believe is happening is the redirect is being modified later on, I assume by customer_address_save_after event. I haven't really dug into that.

I'm really not sure what I'm looking for here, but it seems there should be a way to flag the address with an error that will prevent it from saving (similar to how the core handles a new account if someone enters an email address that already exists), I just can't seem to track down where this is handled in Magento, or more specifically, I can't seem to track down how these errors might be set on the address object.

Was it helpful?

Solution

To prevent saving you just have to throw an exception :-)

So just throw an exception after the redirect is initialized, and everything should should work as intended

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top