2

I am programmatically creating customers and adding billing and shipping addresses to their accounts.

I have put in $customer->loadByEmail($email) so when this script runs a second time it updates a customer instead of saving them again.

At the moment I can not work out how to check if a customer has a specific billing or shipping address (or other additional address) when I want to add an address, so I am re-adding the same addresses when the script runs again.

How do I check if a customer has a specific address?

e.g.

$address_details = array(
    'firstname'  => $firstname,
    'lastname'   => $lastname,
    'street'     => array(
        '0'      => $line1,
        '1'      => $line2,
    )
    'city'       => $city,
    'postcode'   => $postcode,
    'country_id' => 'GB',
    'telephone'  => $tel,
    'parent_id'  => $customer->getId(),
);

if(!$customer->hasAddress($address_details)) {
    //add address
}

I would prefer to steer away from a massive foreach such as:

$customer = Mage::getSingleton('customer/session')->getCustomer();
$hasAddress=false;
foreach ($customer->getAddresses() as $address) {
    if($address->getCity() !== $city) {
        $hasAddress = true;
    }
    //...
}
  • I think there is no other way than the foreach you're talking about and also in the foreach you should not just check for city but also check for the firstname ,lastname and the pincode tool. – Vivek Kumar Apr 6 '17 at 4:38
5

$customer->getAddresses() should return all customer addresses so count($customer->getAddresses()) should return quantity of addresses of customer.

you can check like

if(count($customer->getAddresses()) >= 0)
{
    //Customer has one or more addresses. Your code here
}
2

The address information is stored within the Mage_Customer_Model_Customer so you should be able to create an instance of it with the customer id.

$customer = Mage::getModel('customer/customer')->load($customerId);

Then depending on the type of address that you are looking for you should be able to call one of the following functions.

Primary Billing Address: $model->getPrimaryBillingAddress();

Primary Shipping Address:  $model->getPrimaryShippingAddress();

General Address Selection: $model->getAddressItemById();

Hope it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.