1

I need to get the region_id given the region_code and the country_id, but I cannot manage to achieve it. I've tried using the countryFactory and the regionFactory, but i do not understand what i'm doing wrong.

I have something like this

in the constructor the RegionFactory

public function __construct(
    \Magento\Directory\Model\RegionFactory $regionFactory
) {
    $this->_regionFactory = $regionFactory;
}

function getRegionIdByCode($code){


 $region = $this->_regionFactory->create()
            ->loadByCode($code,$country_id)->getFirstItem();
...
}
//where code is correctly calculated based on a csv with all italian regions

Cannot manage to work with the $region object. I need to do something like $region->getRegionId()

Is it possible??

3

This has to work

$region = $this->_regionFactory->create();
$regionId = $region->loadByCode($code, $country_id)->getId();
1

Try below code:

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$region = $objectManager->create('Magento\Directory\Model\Region')
                        ->loadByCode('CA', 'US');
print_r($region->getData());
?>

Output:

Array
(
    [region_id] => 12
    [country_id] => US
    [code] => CA
    [default_name] => California
    [name] => California
)

Note: Please do not use Object Manager. Instead create function and then call it.

  • i accepted the @Nikolas solution, as it is the one not using object manager, but regionFactory correctly as I needed, even though this is going to work as well and can also be translated with regionFactory like this $region = $this->_regionFactory->create() ->loadByCode($code,$country_id)->getData("region_id"); But a +1 for the suggestion – sissy Oct 17 '17 at 7:17
  • How get all region code and names from country id? – jafar pinjar Sep 1 '18 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.