Magento 2.2: How to Get Country Code Based on Country ID

country-regionsmagento2.2

I wish to get the country code based on country id in checkout page .
I have the country id, How do i pass it to get country code in magento 2

Best Answer

In a Block file,

   public function __construct(
            \Magento\Directory\Model\CountryFactory $countryFactory
        ) {
            $this->_countryFactory = $countryFactory;
        }

    public function getCountryCode($countryId){    
        $country = $this->_countryFactory->create()->load($countryId);
        return $country->getCode();
    }

Call like below

$block->getCountryCode($countryId);
Related Topic