Saturday 22 June 2013

Magento - Create a Drop-Down of Countries

When I first needed to access a collection of countries in Magento I assumed it would work like all other data collections but was shocked to find that this wasn't the case. Rather than store country data in the database, Magento stores country data in an XML file and loads it in on each request. Fortunately though, there are some simple functions that we can use to access country names and codes in Magento.

Get An Array of Country Names/Codes in Magento

?
1
2
3
4
5
6
7
8
9
<?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 or the frontend.

Create a Country Drop Down in the Frontend of Magento

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.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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; ?>

Create a Country Drop Down in the 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.
?
1
2
3
4
5
6
7
8
9
<?php
    $fieldset->addField('country', 'select', array(
        'name'  => 'country',
        'label'     => 'Country',
        'values'    => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
    ));
?>

No comments:

Post a Comment