Magento update customer programmatically


Magento update customer programmatically : Sometimes you need to update the customer details programmatically instead of updating manually. Mage::getModel(‘customer/customer’) is used to update customer details in magento. Here in this tutorial we are going to explain how to update customer details programmatically with example.


For Magento 2.x Refer- Magento 2.x Update Customer Data

Magento update customer address programmatically

You can update the customer details using the model Mage::getModel(‘customer/customer’) as below –

Magento update customer details programmatically:

$email = "abc@example.com";
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if($customer->getId()){     
     $customer->setFirstname($firstName); 
     $customer->setLastname ($lastName); 
     $customer->save();
 }

The above example will update the customer details such as first name, last name etc.

Update Customer Address

Let us have one more example in which we will update the customer address programmatically.

Magento Add / Update customer address programmatically

Mage::getModel(‘customer/address’) is used to update the customer address. Here is an example in which we are going to update the customer address.

Magento Add / Update customer address programmatically:

$customerId = 101;
$shippingData = array(
    'firstname' => $firstName,
    'middlename' => $middleName,
    'lastname' => $lastName,
    'prefix' => $prefix,
    'suffix' => $suffix,
    'company' => $company,
    'street' => $street,
    'country_id' => $country,
    'city' => $city,
    'region_id' => '',
    'region' => $region,
    'postcode' => $postal,
    'country_id' => $country, 
    'telephone' => $telephone,
    'fax' => $fax,
);

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

if ($customer->getDefaultShipping()){
    $defaultShippingId = $customer->getDefaultShipping()
    $customerAddress->load($defaultShippingId); 
} else {   
    $customerAddress
        ->setCustomerId($customerId)
        ->setIsDefaultBilling('0')
        ->setIsDefaultShipping('1')
        ->setSaveInAddressBook('1');
}

try {
    $customerAddress->setData($shippingData);
    $customerAddress->save();
} catch (Exception $e) {
    Mage::log('Error .' . $e->getMessage());
}

The above example will update the customer address. ->setIsDefaultBilling() is used to save the default billing address. If you set ->setIsDefaultBilling(1) it will save customer address as default billing address. ->setIsDefaultShipping() is used to set the default shipping address if you set ->setIsDefaultBilling(1) it will save the default shipping address as customer address. If you want to save this address in address book then set ->setSaveInAddressBook(‘1’) else set ->setSaveInAddressBook(‘0’).


Advertisements

Add Comment

📖 Read More