0

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?

1 Answer 1

2

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();
2
  • Thank You. this is working fine. I was doing the mistake of Shipping ID Aug 13, 2021 at 13:37
  • I need to add this Zone attribute value in the customer address block in the customer dashboard. check the screenshot: nimb.ws/ziaOhB Also, I tried to add a zone column in the address grid but there is no value is getting there. I have tried to print the address array inside this loop: <?php foreach ($_pAddsses as $address) : print_r($address->getData());?> but print_r is not working and page not working Aug 24, 2021 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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