Magento 1.9 – Get Origin Data on Customer Address Save

customer-addressevent-observermagento-1.9modelsave

I'm working on an observer of the customer_address_save_before event. On customer address saving, i've to check if there's changes before doing some actions.

I did something similar for the customer/customer model with some natives methods such as hasDataChanges(), dataHasChangedFor($key) and getOrigData() from the Varien_Object class.

However, when i tried to do it for the customer/address model, i figured out that the _origData property is null. This happens only when the customer address is updated in the front-end. When i update the customer address in the back-end, i do have the correct _origData.

Do you know why does this happen and how to fix or bypass this ?

Best Answer

I fixed the issue a few weeks ago so i'm going to give my solution as it could helps anyone :

public function onCustomerAddressSaveBefore(Varien_Event_Observer $observer)
{
    $customerAddress = $observer->getEvent()->getCustomerAddress();

    /*
     * If the customer address exists, as $_origData of customer's address is sometimes null, we have to set it manually
     */
    if (!$customerAddress->isObjectNew() && !$customerAddress->getOrigData()) {
        $customerOrigAddress = Mage::getModel('customer/address')->load($customerAddress->getId());

        foreach ($customerOrigAddress->getData() as $field => $value) {
            $customerAddress->setOrigData($field, $value);
        }
    }
}

As you might guess, the onCustomerAddressSaveBefore() method is triggered on customer_address_save_before event. Inside it, i check if the object is not new (there's no original data for a new object) and if the object doesn't contain _origData yet. If these conditions are true, then i manually set the _origData by getting them from the database.

Related Topic