When working with Magento, for some specific reasons a developer want to access list of countries to add a drop-down list of country to both front-end and back-end of Magento. How to do this?
In this tutorial we will go through some points:
- Access and get list of Country Names/Codes in Magento
- Add a dropdown list of country to back-end of Magento
- Add a dropdown list of country to front-end of Magento
This method was tested and worked properly in Magento 1.8 and 1.9
Access and get list of Country Names/Codes in Magento
Unlike other platform, Magento store countries data in an XML file and it will load this XML file on each request. We can use the following code to print an array of Country data (Name and code).
$countryList = Mage::getResourceModel('directory/country_collection')
Now we got the data, next we will learn how to add a drop-down list box to Magento (backend and frontend)
Add Drop-down list box to backend
Based on the array we got from step 1, we can use the following code to add drop-list box to Magento backend. We will use PHP to ensure Magento admin pages look neat and uniform.
$fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
Add Drop-down list box to front-end of Magento
For front-end, find the layout file you want to add the drop-down list box to, for example, we will add drop-down list box to Header of your site.
Go to app/design/frontend/rwd/default/template/page/html/header.phtml edit and add the following code:
<?php $_countries = Mage::getResourceModel('directory/country_collection')
<?php if (count($_countries) > 0): ?>
<select name="country" id="country">
<option value="">-- Select Country --</option>
<?php foreach($_countries as $_country): ?>
<option value="<?php echo $_country['value'] ?>">
<?php echo $_country['label'] ?>
<?php endforeach; ?>
<?php endif; ?>
I hope you love this quick and sweet tutorial.