Display Countries Drop Down In Magento



If you are working with the custom Magento development,sometimes it requires to display the Countries Name in frontend or into the admin panel. In this post I am trying to describe how we can display the countries drop down in Magento?. Actually the country data are not stored into the database, so you can not get data from the country collection, Magento stores all the country data in an XML file and loads it on each request.

1. Display Country Drop Down in the Frontend of Magento :

<?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; ?>

Just Copy and paste the above code in any phtml file of the frontend you will get the country dropdown over there.

2. Display Country Drop Down in the Magento Admin

<?php
 
    $fieldset->addField('country', 'select', array(
        'name'  => 'country',
        'label'     => 'Country',
        'values'    => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(), 
    ));
 
?>

Just Copy and paste the above code in any form file of the backend you will get the country dropdown over there.

3. Array of Country in Magento :

<?php
 
    $country_List = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);
     
    echo '<pre>';
    print_r( $country_List);
    exit(); 

?>

The above code will print an array of every country code and country name known to Magento.

This is all about to display the Country dropdown in Magento admin as well as on the Frontend, Keep reading and enjoy the Magento Custom coding.