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.

This entry was posted in PHP, Zend Framework. Bookmark the permalink.

One Response to Zend Form country lists

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>