Update customer address using address id in magento 2
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);
}
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!