The list of countries in Magento doesn’t work like all other data
collections. Rather than store country data in the database, Magento
stores country data in an XML file and loads it in on each request.There were some simple functions we can use to access
country names and codes in Magento. In this post, I will guide you
through how to create a drop-down list of countries in Magento:
Get An Array of Country Names/Codes in Magento
<?php
$countryList = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
echo '<pre>';
print_r( $countryList);
exit(');
?>
The above code will print out an array containing every country code and country name known to Magento.
Drop Downs and Country Information
The most common reason developers access country names in Magento is to create a drop down. There are several ways to accomplish this and they differ depending on whether you’re in the admin (backend) or the frontend.Creating a Country Drop-Down in the Magento Frontend
You can add the following code to any template file in the frontend of Magento and you will get a drop down box using the country name as the label and the country code as the value.
<?php $_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false) ?>
<?php if (count($_countries) > 0): ?>
<select name="country" id="country">
<option value="">-- Please Select --</option>
<?php foreach($_countries as $_country): ?>
<option value="<?php echo $_country['value'] ?>">
<?php echo $_country['label'] ?>
</option>
<?php endforeach; ?>
</select>
<?php endif; ?>
Creating a Country Drop Down in the Backend Magento Admin
When creating forms in the Magento Admin area, it is very rare that we use actual HTML. The reason for this is that forms are generally built using pre-built functions. The benefit of this is that each Admin page looks uniform and helps to keep Magento looking like one whole application rather than having loads of bits stuck onto it. As our method of adding HTML changes, so must our method of creating our country drop down.
<?php
$fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
));
?>
I hope you find this tutorial helpful!