When we think about countries collection in our programming knowledge we must first think there would database collection, but in magento that doesn’t happen. That happens through XML files and loads on each request, it doesn’t store country information in database. So here our concern is how we can Create dropdown of countries in frontend and backend as well. Well it’s a very tricky to do that . let see I am going to show you both ideas of frontend and backend.

Create dropdown of countries in magento
Create dropdown of countries in magento

Front End Postion:

You can use below code in any template file that you want to show over that location.

<?php $countries = Mage::getResourceModel('directory/country_collection')->loadData()->toOptionArray(false); ?>
<?php if(count($countries) > 0): ?>
<select name="country" id="country">
    <option value="">--- Please select country ---</option>
    <?php foreach($countries as $_country): ?>
        <option value="<?php echo $_country['value'] ?>"><?php echo $_country['label'] ?></option>
    <?php endforeach; ?>
<?php endif; ?>

Back End Position:

Generally in magento backend form we don’t use any custom HTML attributes , because forms are build using pre-build function. So here we will follow magento syntax to add our custom html elements as country drop in that form. So lets see how easy to Create dropdown of countries in magento admin form.

                    'name' => 'country',
                    'label' => 'Country',
                    'value' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),

So finally from above two situatio we got to know we can collect country collection from anywehre in mganeto by following code:

$countries = Mage::getResourceModel('directory/country_collection')->loadData()->toOptionArray(false);

if you will see the log file then you will be getting all list of countries with their codes

also we can get that by system configuration filed section that is:

$countries = Mage::getModel('adminhtml/system_config_source_country')->toOptionArray();

Same way here you can see your all country details through log file

Hope you enjoyed this article and will never forge to share to help other

Thank You

Create dropdown of countries
Tagged on:                         

Leave a Reply

Your email address will not be published. Required fields are marked *