How to get the country code based on country id in magento 2
-
16-02-2021 - |
Pergunta
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
Solução
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);
Outras dicas
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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange