How to Get Region Code by Region ID in Magento 2

How to Get Region Code by Region ID in Magento 2

Hello Magento Friends,

How are you all? Today I am here to demonstrate How to Get Region Code by Region ID in Magento 2. By chance, you missed out on our previous blog, How to Create QR Code of invoice ID and add it to Magento 2 invoice PDF.

Introduction:

In today’s world, it is possible to deliver products to any corner. Magento provides the functionality to run a multinational functioning store. At the time of building delivery and payment related extensions or customization, there is a need for region details in Magento 2. You can get Region Code by Region ID in Magento 2.

Here we are getting region code with the help of the order Increment Id method.

Steps to Get Region Code by Region ID in Magento 2:

Step 1: Go to the below path

app\code\Vendor\Extension\Helper\Data.php

And add the code as shown below.

<?php
namespace Vendor\Extension\Helper;

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()
    {
       // load order using order increment id
        $orderIncrementId = 000000010;
        $order = $this->orderFactory->create()->loadByIncrementId($orderIncrementId);

        $billingAddress = $order->getBillingAddress()->getData();
        $region = $this->regionFactory->create()->load($billingAddress['region_id']);

        // to get all region data
        $this->_logger->info(print_r($region->getData(), true));

        return $region->getCode();
        
    }
}

The result of this we will get in an array format as shown below:

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

This way you will get the state code, state name, and use it wherever required.

Conclusion:

Therefore, this way you can Get Region Code by Region ID in Magento 2. If you have any trouble with the execution of the above steps, mention it in the comment part. Make sure to share the article amongst your Magento friends and keep in touch with us.

Happy Coding

Previous Article

How to Create Custom Form in Magento 2 Frontend

Next Article

Magento 2: How to Get Order Details with Custom Extension Attributes using REST API

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨