Magento, Magento 2

How to Get Country Name By Country Code in Magento 2

How to Get Country Name By Country Code in Magento 2

In this tutorial, Today I will explain to how to get country name by country code in Magento 2. To get country name by country code, you need to use \Magento\Directory\Model\CountryFactory class in your construct.

You may also like this :

Let’s see the below code to get country name using country code in Magento 2 :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

use Magento\Directory\Model\CountryFactory;

class CustomerDetails extends \Magento\Framework\View\Element\Template
{
    /**
     * @var CountryFactory
     */
    protected $countryFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param CountryFactory                                   $countryFactory
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        CountryFactory $countryFactory,
        array $data = []
    ) {
        $this->countryFactory = $countryFactory;
        parent::__construct($context, $data);
    }

    public function getCountryName($countryCode)
    {
        $countryObj = $this->countryFactory->create()->loadByCode($countryCode);
        if ($countryObj) {
            $countryName = $countryObj->getName();
        }
        return $countryName;
    }
}

You can use this above code in block and model file. You just need to pass country code in getCountryName($countryCode) function to retrieve country name. If you want to get full object of country by country code then, you just need to print $countryObj variable. It will return full object of country data by country code.

Aftet that, inject class in construct Now, just need to remove generated and clean cache.

That’s it !!!

I hope this blog is easy to understand about how to get country name by country code in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

 

Tagged ,