Magento 1.9 Adminhtml – Use iso3_code in Country List

adminhtmlbackendcollection;magento-1.9model

I have a dropdown list on the Magento backend extension that I'm developing.

So far, the working code for this dropdown is as follows:

$fieldset->addField(
'country',
'select',
array(
'name' => 'country',
'class' => 'required-entry',
'required' => true,
'label' => 'Country',
'values' => Mage::getModel('directory/country')->getCollection()->toOptionArray(),
));

It works well but doesn't deliver what I'm looking for. Yes, it adds the full list of countries on the backend, but it saves the values with the iso2_code instead of the iso3_code column on directory_country, so instead of saving USA it saves the value US

I've tried adding addAttributeToSelect and addAttributeToFilter but both throw the errors:

Invalid method Mage_Directory_Model_Country::addAttributeToSelect(Array ( [0] => iso3_code ) )

Invalid method Mage_Directory_Model_Country::addAttributeToFilter(Array ( [0] => iso3_code ) )

Could you guys please help me?

Best Answer

There may be a better way, but adding a helper method to your form like this should work.

protected function _getCountryOptions() {
    $sort = array();
    $collection = Mage::getModel('directory/country')->getCollection();
    foreach($collection as $country) {
        $name = Mage::app()->getLocale()->getCountryTranslation($country->getData('iso2_code'));
        if (!empty($name)) {
            $sort[$name] = $country->getData('iso3_code');
        }
    }
    Mage::helper('core/string')->ksortMultibyte($sort);
    $options = array();
    foreach ($sort as $label=>$value) {
        $options[] = array(
           'value' => $value,
           'label' => $label
        );
    }

    return $options;
}

And then:

$fieldset->addField('country', 'select', array(
    'name'     => 'country',
    'class'    => 'required-entry',
    'required' => true,
    'label'    => 'Country',
    'values'   => $this->_getCountryOptions(),
));
Related Topic