Drowned World

Same kind of moon, same kind of jungle.

Zend Form country lists

One task that comes up time and time again is creating a dropdown form element that is populated by a list of countries. In the past I solved this problem by keeping an key/value array of countries and their codes and loaded this in via a loop. Not any more. By using Zend_Locale and Zend_Form you can automate this task in a few lines of code.

$locale = new Zend_Locale('en_Gb');
$countries = ($locale->getTranslationList('Territory', 'en', 2));
asort($countries, SORT_LOCALE_STRING);

$form = new Zend_Form();
$country = new Zend_Form_Element_Select('country');
$country->setLabel('Country')
        ->addMultiOptions($countries)
        ->setValue('GB');
$form->addElement($country);

You can take this one step further and create a custom element to display country dropdowns but I’ll leave that to you.

One ResponseLeave one →

  1. This is handy. I’ll have to remember this one in the future :)

Leave a Reply