5

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.

1 Answer 1

6
$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.

13
  • $address->setRegion() i used, but its not working Commented Sep 3, 2018 at 6:00
  • What value did you put in region? It should exist in database. Commented Sep 3, 2018 at 12:59
  • my issue is similar to this one, I need to update address from request magento.stackexchange.com/questions/240352/… Commented Sep 3, 2018 at 13:35
  • hi @Milind, This is not working for me Commented Dec 4, 2018 at 8:07
  • Hi @jafarpinjar I have updated the code obtain the region_id Commented Dec 5, 2018 at 13:02

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.