Question

I am trying to fetch customer addresses on a custom page using below code.

$shipId = 'VALID SHIPPING ADDRESS ID';
$billId = 'VALID BILLING ADDRESS ID';
$addressObject = Mage::getModel('customer/address');
$shipAddress = $addressObject->load($shipId);
$billAddress = $addressObject->load($billId);

But I don't know why I am getting only the billing address data in $shipAddress and $billAddress.
Actually I am getting the address which is lower in the order. For example if modify the code like below

$billAddress = $addressObject->load($billId);
$shipAddress = $addressObject->load($shipId);

Now I am getting the shipping address in both the variables.
Please let me know what is the issue here and how this can be fixed.

Was it helpful?

Solution

You have a misconception in how Magento models work.

They are not "loaders" which just give you back a data object.

They represent the entity itself and load themselves (this is called "Active Record").

So you have a model $addressObject and load it twice, from different ids. The second load overwrites the data from the first load.

Your code only works because load() happens to return $this for convenience. In the end $billAddress, $shipAddress and $addressObject all hold the identical object. Objects in PHP are not copied when you assign them to a different variable, the variable only holds a reference to the actual object.

Correct code:

$billId = 'VALID BILLING ADDRESS ID';
$shipAddress = Mage::getModel('customer/address')->load($shipId);
$billAddress = Mage::getModel('customer/address')->load($billId);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top