简体   繁体   中英

Create a customer address to already exist customer - Magento

I'm trying create programmatically a new address to customers that was imported a some time ago for me.

My Code:

//All variables about customer address info are filled
$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);

if($customer->getId()) {
    $addressData =  array (
        'firstname' => $customer->getFirstname(),
        'lastname' => $customer->getLastname(),
        'street' => "$_s1
$_s2
$_s3
$_s4",
        'city' => $_city,
        'country_id' => 'BR',
        'region_id' => $_regionid,
        'postcode' => $_cep,
        'telephone' => $_tel,
        'celular' => $_cel,
        'is_default_billing' => 1,
        'is_default_shipping' => 1
    );

    $address = Mage::getModel('customer/address');
    $address->addData($addressData);
    $customer->addAddress($address);

    try {
        print_r($addressData);
        $customer->save();
    }
    catch (Exception $e) {
    }
}

Object loaded '$customer' isnt what I need: a full customer object. Any Idea?

You have to save customer address in different way, following is address saving code.

$customerAddress = Mage::getModel('customer/address');

$customerAddress->setData($addressData)
        ->setCustomerId($customer->getId())
        ->setSaveInAddressBook('1');

$customerAddress->save();

The full code will look like:

$customerModel = Mage::getModel('customer/customer');
$customer = $customerModel->setWebsiteId(1)->loadByEmail($_email);

if($customer->getId()) {
    $addressData =  array (
        'firstname' => $customer->getFirstname(),
        'lastname' => $customer->getLastname(),
        'street' => "$_s1
$_s2
$_s3
$_s4",
        'city' => $_city,
        'country_id' => 'BR',
        'region_id' => $_regionid,
        'postcode' => $_cep,
        'telephone' => $_tel,
        'celular' => $_cel,
        'is_default_billing' => 1,
        'is_default_shipping' => 1
    );

    $customerAddress = Mage::getModel('customer/address');

    $customerAddress->setData($addressData)
        ->setCustomerId($customer->getId())
        ->setSaveInAddressBook('1');

    $customerAddress->save();

    //And reload customer object
    $customer = Mage::getModel('customer/customer')->load($customer->getId());
    //Check customer data
    print_r($customer->getData());
    //Check addresses
    foreach($customer->getAddresses() as $address)
    {
        print_r($address);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM