0

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?

1
  • You're trying to filter a single entity (the model) instead of the selection of entities (the collection). See the getCollection() call in your code.
    – user4351
    Feb 24, 2015 at 20:32

1 Answer 1

4

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(),
));
3
  • Thanks for your prompt reply. I have some questions though. Where shall I place the helper? I have the typical adminhtml block form with tab, so I have grid.php, edit.php, edit folder with tabs.php, form.php and tab folder with country.php . Then I also have the models with resources, controllers, helpers, etc.
    – VDD
    Feb 24, 2015 at 21:19
  • Sorted. It works right away. Thank you very much. I've marked the answer as correct, but I can't upvote it because it requires +15 of reputation, sorry. I'll upvote once I have the reputation.
    – VDD
    Feb 24, 2015 at 21:27
  • Upvoted for you
    – RRStoyanov
    Feb 25, 2015 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.