0

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

2

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);
| improve this answer | |
1

I am not very much sure about your query.

here is my suggestions may help you.

country_code has two types in the directory_country table. 1)iso2_code and 2) iso3_code

Whereas, iso2_code and country_id is similar. If you want to get 3 digits of country_code, then proceed with iso3_code.

Like this, $country->getData('iso3_code')

protected $_country;

public function __construct(
    \Magento\Directory\Model\Country $country
) {
    $this->_country = $country;
}

public function getCountryname() {
    $countryCollection = $this->_country->getCollection();
    foreach ($countryCollection as $country) {
       $countryId = $country->getCountryId();
       $iso3Code = $country->getData('iso3_code');
    }
    echo $countryId;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.