12

Like in magento1 is is there any method to retrive region name by id.

$regionModel = Mage::getModel('directory/region')->load('region_id'); 
$region = $regionModel->getName();

I checked respective class(Magento\Directory\Model\Region) but didn't find any method there.

2 Answers 2

17

You still can do basically the same as load(), save(), and delete() actions still exists in abstract model classes. They are however marked as deprecated as magento moves CRUD methods to separate repositories classes. But since directory model does not have them yet here are 2 ways of loading the region.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$region = $objectManager->create('Magento\Directory\Model\Region')
                        ->load($regionId);

or with collection

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$region = $objectManager->create('Magento\Directory\Model\ResourceModel\Region\Collection')
                        ->addFieldToFilter('region_id', ['eq' => $regionId])
                        ->getFirstItem();

This is just proof-of-concept code. Direct use of object manager is discouraged so in your actual code you should inject the proper class with dependency injection in __construct() class.

1
  • Great. Its work.
    – Kul
    Commented Jul 15, 2017 at 14:27
7

You can achieve this goal using a collection and the getItemById() method. Something like that:

<?php

use Magento\Directory\Model\ResourceModel\Region\Collection  as RegionCollection;

class Example
{
    /** @var RegionCollection  */
    private $regionCollection;
    
    public function __construct(
        RegionCollection $regionCollection
    ) {
        $this->regionCollection = $regionCollection;
    }

    /**
     * @param int $id
     * @return string
     */
    private function getRegionNameById(int $id): string
    {
        $region = $this->regionCollection->getItemById($id);

        return $region->getCode();
    }
}

See you later!

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.