[eluser]Watermark Studios[/eluser]
I had a difficult time finding an up-to-date array of ISO 3166-1-alpha-2 country codes, so I created my own array and a helper function. There is a better place to store the array than in the helper, like in the application/config/config.php file, but I thought it would be easier to follow by just looking at the code below.
I wanted an array to be passed as a parameter that directs the helper to customize the first few options. Most companies only operate in a few countries, but they want all countries to be available. So I created the below helper extension.
Just create a file in application/helpers called MY_form_helper.php
You can load the helper like you would normally load a helper in a controller
Code:
$this->load->helper('form');
and call the function in a view
Code:
<?php echo country_dropdown(); ?>
The first parameter in the function is the name of the selection element and the second is an array of the countries in ISO 3166-1-alpha-2 code elements. For example
Code:
<?php echo country_dropdown('country',
array('US','CA','GB','DE','BR','IT','ES','AU','NZ','HK'));?>
would return a list of all countries in the ISO 3166 list with the 10 countries in the array at the top of the list.
Below is the function for MY_form_helper.php
Code:
function country_dropdown($name="country", $top_countries=array()){
$countries = array(
"AF"=>"Afghanistan",
"AL"=>"Albania",
"DZ"=>"Algeria",
"AD"=>"Andorra",
"AO"=>"Angola",
"AI"=>"Anguilla",
"AQ"=>"Antarctica",
// list of countries continues until Zimbabwe
"ZW"=>"Zimbabwe"
);
$html = "<select name='{$name}'>";
if(!empty($top_countries)){
foreach($top_countries as $value){
if(array_key_exists($value, $countries)){
$html .= "<option value='{$value}'>{$countries[$value]}</option>";
}
}
$html .= "<option>----------</option>";
}
foreach($countries as $key => $country){
$html .= "<option value='{$key}'>{$country}</option>";
}
$html .= "</select>";
return $html;
}
I hope someone can benefit from this...it's such a common requirement, and I'm sure there are posts in this forum somewhere, but I had a difficult time finding them.