region Id error on updating address using address Id in magneto2
Question
I followed below link to update address using address id
Update customer address using address id in magento 2
I am getting this error upon executing this code
protected $addressRepository;
public function __construct(
\Magento\Customer\Api\AddressRepositoryInterface $addressRepository
) {
$this->addressRepository = $addressRepository;
}
public function changeAddress($addressId)
{
$AddressId = 381993;
if(isset($AddressId) && $AddressId !=''){
try{
$address = $this->addressRepository->getById($AddressId);
$address->setFirstname('test');
$address->setLastname('test');
$address->setCountryId('GB');
$address->setRegion()->setData(array('region' => 'test'));
$address->setPostcode('t9 1rd');
$address->setCity('test');
$this->addressRepository->save($address);
}catch(\Exception $e){
print_r($e->getMessage());
}
}
}
I am getting this error upon using this code
"message": "Invalid value of \"1\" provided for the regionId field.",
I tried
$address->setRegion(); also same error again
What is the mistake in above code? Please anyone help me.
Solution
$countryId = 'US' //static set for example
$regionName = 'Alaska' //static set for example
/** @var \Magento\Directory\Model\Region $region */
$region = $this->regionFactory->create();
$region->loadByName($regionName, $countryId);
// load region on the
// basis of state name and country id
$regionId = $region->getRegionId(); // obtain region_id
$address = $this->addressRepository->getById($AddressId);
$address->setFirstname('test');
$address->setLastname('test');
$address->setCountryId('US');
if (isset($regionId)) {
$address->setRegionId($regionId);
}
$address->setPostcode('t9 1rd');
$address->setCity('Test City');
$this->addressRepository->save($address);
By default "region" is required if the selected "country" have dat for states or cities, else "region" is not needed. (You have set an empty region $address->setRegion())
Also, "region_id" is the primary key for the region should be the same as in database.
Try to run the above sample and check.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange