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 !=''){
                $address = $this->addressRepository->getById($AddressId);
                $address->setRegion()->setData(array('region' => 'test'));
                $address->setPostcode('t9 1rd');
             }catch(\Exception $e){


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.

1 Answer 1

$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);
if (isset($regionId)) {
$address->setPostcode('t9 1rd');
$address->setCity('Test City');

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.


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.