Welcome Guest, Not a member yet? Register   Sign In
Easy country drop-down using a form helper extension - ISO 3166
#1

[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.
#2

[eluser]richthegeek[/eluser]
I can see this being helpful

It might be worthwhile putting the countries list in a config file, and/or perhaps allow users to create pre-defined sets which they can pass to the function as a string (eg, I pass 'G4' and get array( "US", "GB", "FR", "RU" )).

It also has no function for *only* showing the $top_countries argument in the list, if the user wanted to exclude all but those passed, for example in a shopping cart ordering form (only shipping to UK and FR or whatever).

Good job anyway.
#3

[eluser]Watermark Studios[/eluser]
Okay, I made a little change to my helper. You can expand the parameters to your heart's desire, but I don't really want to get too far out there. I do have 4 parameters now, which is a bit more than I like, but it does what has been suggested. First off, I put my country array in application/config.php
Code:
$config['country_list'] = array(
             "AF"=>"Afghanistan",
             "AL"=>"Albania",
             "DZ"=>"Algeria",
// Through Zimbabwe
             "ZW"=>"Zimbabwe");

Now I can call the country_list array from anywhere with
Code:
config_item('country_list');

So, I rewrote my helper extension as below to accept 4 parameters: 1) Select field name, 2) Top countries, 3) Selected country, 4) Show all countries (true = shows all, false = shows only top countries). The only caution I have is that the casing for 3166-1-alpha-2 codes are the same in your config array as they are in your parameters. I tried calling some "strtoupper" functions and everything worked except with the last parameter. I'll post another post with the country array since all the ones I look for online are out of date.
Code:
function country_dropdown(
                          $name="country",
                          $top_countries=array(),
                          $selection=NULL,
                          $show_all=TRUE)
{
  $countries = config_item('country_list');
  $html = "<select name='{$name}'>";
  $selected = NULL;
  if(in_array($selection,$top_countries)){
    $top_selection = $selection;
    $all_selection = NULL;
  } else {
    $top_selection = NULL;
    $all_selection = $selection;
  }
  if(!empty($top_countries)){
    foreach($top_countries as $value){
      if(array_key_exists($value, $countries)){
    if($value === $top_selection){
      $selected = "SELECTED";
    }
    $html .= "<option value='{$value}' {$selected}>{$countries[$value]}</option>";
    $selected = NULL;
      }
    }
    $html .= "<option>----------</option>";
  }
  if($show_all){
    foreach($countries as $key => $country){
      if($key === $all_selection){
    $selected = "SELECTED";
      }
      $html .= "<option value='{$key}' {$selected}>{$country}</option>";
      $selected = NULL;
    }
  }
  $html .= "</select>";
  return $html;
}
#4

[eluser]jedd[/eluser]
This, and the config you posted, look really handy - I've pinched them and stuck them in my 'to use in my next project' helper directory.

Thanks you for doing and sharing this. You may want to look at migrating this to the wiki? If you're not inclined to, can you drop me a PM and I'll add it to my 'migrate to the wiki' to-do list.
#5

[eluser]Watermark Studios[/eluser]
Feel free to pinch. I wasn't planning on migrating to wiki, but that may be a good idea.
#6

[eluser]jedd[/eluser]
Done and done.

For future reference - if you want to update anything, I'd suggest you change the wiki - and for any wanderers looking for the latest version of this:

[url="/wiki/helper_dropdown_country_code/"]Helper Dropdown - Country Code[/url]

The Wiki has a very basic category / tagging system - but it's a bit crapped-out mostly due to people's inability to settle on any kind of standard, combined with most people's inability to spell, and augmented by most people's breathtaking levels of laziness, and certainly not helped by most people's rampant desire to avoid contemplative thought. (I probably shouldn't read John Ralston Saul before dinner.)

Anyway, I mention this to explain why I didn't bother trying to put this into a category. It'll come up on searches for '3166', 'country helper' and 'country code' - which should be good enough I think.
#7

[eluser]webdevguy[/eluser]
Thank you kindly for this choice bit of code! It seems like the sort of thing we might want to add to the core.
#8

[eluser]Oleg Videnov[/eluser]
Thanks a lot.
You just saved me a looot of time.I am going to use this handy helper in my future projects.
#9

[eluser]Reza Valinezhad[/eluser]
Some countries are not in the list, like Iran.
#10

[eluser]jedd[/eluser]
[quote author="Reza Valinezhad" date="1306098636"]Some countries are not in the list, like Iran.[/quote]

Please update the wiki.




Theme © iAndrew 2016 - Forum software by © MyBB