How can I update customer address by address id in Magento 2 programmatically ?
Asked
Active
Viewed 1.2k times
2 Answers
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);
}
Siarhey Uchukhlebau
- 15,957
- 11
- 54
- 83
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!
Tirth Patel
- 1,039
- 8
- 26
NoSuchEntityExceptionand create a new address entity from scratch (using the address factory). Then you can proceed using code from the answer. If you want to get more detailed answer, please write you own question with code you are using and give me a link. I will try to help you :) – Siarhey Uchukhlebau May 26 '22 at 09:52