4

How can I update customer address by address id in Magento 2 programmatically ?

2 Answers 2

9

If you know the address id ($addressId) you can use the address repository to load and save updated addresses:

/**
 * @var \Magento\Customer\Api\AddressRepositoryInterface
 */
protected $addressRepository;

/**
 * Sync constructor.
 * @param \Magento\Customer\Api\AddressRepositoryInterface $addressRepository
 */
public function __construct(
    \Magento\Customer\Api\AddressRepositoryInterface $addressRepository
) {
    $this->addressRepository = $addressRepository;
}

public function changeAddress($addressId)
{
    /** @var \Magento\Customer\Api\Data\AddressInterface $address */
    $address = $this->addressRepository->getById($addressId);
    $address->setCity('customCity'); // Update city
    $address->setCountryId('UK'); // Update country id 
    // update what ever you want
    $this->addressRepository->save($address);
}
14
3

If you want to Update address by addressID with region details

Use below code

$adddress_id = 12;
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$address = $obj->create('\Magento\Customer\Model\Address')->load($adddress_id);
$address->setTelephone('7894561230')
        ->setCountryId('US')
        ->setPostcode('12345-6789)
        ->setCity('boston')
        ->setRegionId(57)
        ->setRegionCode('TX')
        ->setRegion('Texas')
        ->setStreet('102 san diago') //you can also pass array for street
        ->setSaveInAddressBook('1')
        ->setIsDefaultShipping('1')
        ->save();

NOTE: You should not use the ObjectManager directly!

Your Answer

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

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