In the world of drone delivery, there is no boundary, and businesses can deliver products and services to the customers around the corner. With Magento, one can run an internationally operated online store.
In most instances, while developing extensions or customization based on delivery and payment gateway, you need to avail the region data. Earlier, I provided the solution to get region ID by region & country code in Magento 2.
Generally, it is a small matter of task, if the requirement is related to the region name. However, it’s a little bit tricky when the need arrives to get region code by region ID in Magento 2.
Ever faced an issue for getting a region code by region ID ? The below code shows the steps to get region code by region ID in Magento 2.
Steps to Get Region Code by Region ID in Magento 2
- Create Data.php in Vendor\Extension\Helper and use the following solution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <?php use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Magento\Sales\Model\OrderFactory; class Data extends AbstractHelper { protected $orderFactory; protected $regionFactory; public function __construct( Context $context, OrderFactory $orderFactory, RegionFactory $regionFactory ) { $this->orderFactory = $orderFactory; $this->regionFactory = $regionFactory; parent::__construct($context); } public function getOrderRegionData() { $orderId = 3; // load order using order id $order = $this->orderFactory->create()->load($orderId); // OR load order using order increment id $orderIncrementId = 00022; $order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId); $billingAddress = $order->getBillingAddress()->getData(); $region = $this->regionFactory->create()->load($billingAddress['region_id']); // to get/print all region data $this->_logger->info(print_r($region->getData(), true)); return $region->getCode(); } } |
- Using order ID
- Using order increment ID
Here the returned region code is ‘AN’.
$this->_logger->log(print_r($region->getData(), true)) prints array log as mentioned below:
1 2 3 4 5 6 7 | Array ( [region_id] => 533 [country_id] => IN [code] => AN [default_name] => Andaman and Nicobar Islands [name] => Andaman and Nicobar Islands ) |
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.