Magento 2 You can get Region Code by Region name using Directory Module.
You can get region code from region name by Magento\Directory\Model\ResourceModel\Region\CollectionFactory object.
Let’s check with Region name is California and we want to get region code CA from California.
<?php
namespace Path\To\Classname;
use Magento\Directory\Model\ResourceModel\Region\Collection;
use Magento\Directory\Model\ResourceModel\Region\CollectionFactory;
class GetRegionCode {
/**
* @var Collection
*/
private $collectionFactory;
public function __construct(
CollectionFactory $collectionFactory
) {
$this->collectionFactory = $collectionFactory;
}
/**
* @param string $region
* @return string[]
*/
public function getRegionCode(string $region): array
{
$regionCode = $this->collectionFactory->create()
->addRegionNameFilter($region)
->getFirstItem()
->toArray();
return $regionCode;
}
}
Call $this->getRegionCode(“California”);
The result will be,
Array
(
[region_id] => 12
[country_id] => US
[code] => CA
[default_name] => California
[name] => California
)
