Reputation: 5260
I have tried to find country code by country name. So, for example, I have "Netherlands", I need to get "NL"
I know there is method to find name form code:
$country_name = Mage::app()->getLocale()->getCountryTranslation($country_code)
But I need vice versa.
So is there any methods in Magento to resolve it?
Upvotes: 4
Views: 14975
Reputation: 11
in Magento 2 there is a lack of simple processes so i suggest you to use the zend framework like :
$countryId = array_search($countryName, \Zend_Locale::getTranslationList('territory'));
Don't forget to make sure your country name is capitalized.
Upvotes: 1
Reputation: 311
This works for me
$list = Mage::app()->getLocale()->getCountryTranslationList(); $list=array_flip($list);
echo $list['United States'];
Upvotes: 5
Reputation: 199
There is a way to get Country ID without loading countries collection. As all country IDs mapped with names are stored in XML you can access that XML by locale object.
$list = Mage::app()->getLocale()->getCountryTranslationList();
foreach ($list as $id => $name) {
if ($name == $countryName) {
return $id;
}
}
Please note that country name should be translated to the current locale language. Otherwise change locale to necessary one:
$oldCode = Mage::app()->getLocale()->getLocaleCode();
Mage::app()->getLocale()->setLocaleCode('en_US');
...
...
...
Mage::app()->getLocale()->setLocaleCode($oldCode);
Upvotes: 2
Reputation: 1662
the country collection
<select title="Country" class="validate-select" id="billing:country_id" name="billing[country_id]">
<option value=""> </option>
<?php
$collection = Mage::getModel('directory/country')->getCollection();
foreach ($collection as $country)
{
?>
<option value="<?php echo $country->getId(); ?>"><?php echo $country->getName(); ?></option>
<?php
}
?>
</select>
Upvotes: 0
Reputation: 13812
From the other question, this can only be done by looping through the country collection
$countryId = '';
$countryCollection = Mage::getModel('directory/country')->getCollection();
foreach ($countryCollection as $country) {
if ($countryName == $country->getName()) {
$countryId = $country->getCountryId();
break;
}
}
echo $countryId;
Because of how the data is stored in the XML there is no way to filter or load by name.
Upvotes: 5