Create a Drop-Down of Countries

piaoling  2011-06-21 17:32:14

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<p></p>
<p> $countryList = Mage::getResourceModel('directory/country_collection')<br>
                    ->loadData()<br>
                    ->toOptionArray(false);</p>
<p> echo '<pre>';<br>
    print_r( $countryList);<br>
    exit('</pre>');</p>
<p>?>
</p>

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')<br>
                                    ->loadData()<br>
                                    ->toOptionArray(false) ?><br>
<?php if (count($_countries) > 0): ?><br>
    <select name="country" id="country"><br>
        <option value="">-- Please Select --</option><br>
        <?php foreach($_countries as $_country): ?><br>
            <option value="<?php echo $_country['value'] ?>"><br>
                <?php echo $_country['label'] ?><br>
            </option><br>
        <?php endforeach; ?><br>
    </select><br>
<?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
<?php<p></p>
<p> $fieldset->addField('country', 'select', array(<br>
        'name'  => 'country',<br>
        'label'     => 'Country',<br>
        'values'    => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),<br>
    ));</p>
<p>?>
</p>

This post was posted in General

类别 :  magento(258)  |  浏览(3234)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: