Reputation: 171
When a customer enters an address for the first time than this address serves as billing and shipping address. But there is only one entry in the database. So if the customer later decides to alter the shipping address by editing the existing one than the billing address is changed too. To prevent this, I need two separate entries in the database, one for the billing address and one for the shipping address. Therefore,
I wrote an event observer using the event customer_address_save_after
to check if the entry for the default billing address is identical to the entry of the default shipping address. If so a copy of this address is saved serving as new shipping address. Well, at least this was the idea,
public function customerAddressSaveAfter($observer)
{
$session = Mage::getSingleton('customer/session');
if ($session->getCustomer()->getDefaultBilling() ==
$session->getCustomer()->getDefaultShipping())
{
$address = $observer->getCustomerAddress();
$address->unsAddressId()
->unsAddressType();
Mage::getModel('customer/address')
->setData($address->getData())
->setIsDefaultShipping('1')
->setSaveInAddressBook('1')
->save();
}
return $this;
}
but running the code seems to result in an infinite loop until the memory is exhausted. What am I doing wrong?
Upvotes: 3
Views: 2133
Reputation: 12706
The problem here is infinite recursion because you are saving a 'customer/address' in a 'customer/address' save event.
Set some attribute on your duplicate, and check for it before saving:
public function customerAddressSaveAfter($observer)
{
$address = $observer->getCustomerAddress();
if ($address->getIsDuplicate()) {
return $this;
}
$session = Mage::getSingleton('customer/session');
if ($session->getCustomer()->getDefaultBilling() ==
$session->getCustomer()->getDefaultShipping())
{
$address->unsAddressId()
->unsAddressType();
Mage::getModel('customer/address')
->setData($address->getData())
->setIsDefaultShipping('1')
->setSaveInAddressBook('1')
->setIsDuplicate(true)
->save();
}
return $this;
}
Upvotes: 1