Magento – magento 1.9 programmatically add / update record

magento-1.9programmatically

What is the way to programmatically Update an existing record, and Add a new one if the record is not found in Magento 1.9?

I have the following code, and what I want it to do is to add a new address to a customer, and update the address if it's found by the address_code(a custom field). But right now the code always Add a new address, even if the address with the same address_code already found in the database.

    $customAddress = Mage::getModel('customer/address')
        ->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('address_code', $address_code)
        ->getFirstItem()
        ->addData($_custom_address)
        ->setCustomerId($customer->entity_id)
        ->save();

What did I do wrong?

Best Answer

Check the below steps:

  1. If you have created the $address_code as a customer attribute and set 'used_in_forms' properly.

    $usedInForms = array(
        'customer_account_create',
        'customer_account_edit',
        'checkout_register',
        'adminhtml_customer'
    );
    
    
    $attribute->setData('used_in_forms', $usedInForms);
    
  2. If the value of $address_code is being posted while update.