Magento 2 – How to Save Customer Address Attribute After Order Success Event

customer-addresscustomer-address-attributemagento2.3.5

I have added a new shipping address (without saving it in the address book) on the checkout page to place an order.

I want to update the existing default shipping address value (zone attribute only) from the new address after the order is successful.

I have used an event: checkout_onepage_controller_success_action

Observer code to set the zone attribute value

$addressFactory  = $this->objectManager->get('\Magento\Customer\Model\AddressFactory');
$address = $addressFactory->create();

        if($orderedZone != $existingZone && $existingZone != ''){
            $address->setZone($newZone);
            $address->save($address);
        }

But after this code I am getting an error like this:

Exception #0 (Magento\Framework\Validator\Exception): "Country" is a required value.
"First Name" is a required value.
"Last Name" is a required value.
"Zip/Postal Code" is a required value.
"Street Address" is a required value.

These fields are already set in the default shipping address.

how can I set only the zone attribute from the new address?

Best Answer

You need to do the code like this one.

    protected $_customerFactory;
    protected $_addressFactory;
 
    public function __construct(
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Model\AddressFactory $addressFactory)
    {
        $this->_customerFactory = $customerFactory;
        $this->_addressFactory = $addressFactory;
    }
 
    //PASS Your CUSTOMER ID here instade of 32
    $customer = $customerFactory->create()->load(32);    
 
    //Shipping Address
    $shippingAddressId = $customer->getDefaultShipping();
    $shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);

    //now you can update your address here and don't forget to save
    $shippingAddress->setZone("YOURNEWVALUE");
    $shippingAddress->save();