Part of the EllisLab Network
   
 
Easy country drop-down using a form helper extension - ISO 3166
Posted: 16 January 2010 12:53 AM   [ Ignore ]  
Summer Student
Total Posts:  13
Joined  10-14-2009

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

$this->load->helper('form');

and call the function in a view

<?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

<?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

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.

Profile
 
 
Posted: 16 January 2010 02:49 AM   [ Ignore ]   [ # 1 ]  
Lab Assistant
Avatar
RankRank
Total Posts:  231
Joined  03-30-2008

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.

Profile
 
 
Posted: 16 January 2010 07:59 PM   [ Ignore ]   [ # 2 ]  
Summer Student
Total Posts:  13
Joined  10-14-2009

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

$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

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.

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;
}
Profile
 
 
Posted: 17 January 2010 05:18 AM   [ Ignore ]   [ # 3 ]  
Lab Technician
Avatar
RankRankRankRank
Total Posts:  2052
Joined  06-04-2008

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.

Profile
 
 
Posted: 17 January 2010 12:24 PM   [ Ignore ]   [ # 4 ]  
Summer Student
Total Posts:  13
Joined  10-14-2009

Feel free to pinch. I wasn’t planning on migrating to wiki, but that may be a good idea.

Profile
 
 
Posted: 17 January 2010 01:23 PM   [ Ignore ]   [ # 5 ]  
Lab Technician
Avatar
RankRankRankRank
Total Posts:  2052
Joined  06-04-2008

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:

Helper Dropdown - Country Code

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.

Profile
 
 
Posted: 31 January 2010 10:59 PM   [ Ignore ]   [ # 6 ]  
Summer Student
Total Posts:  3
Joined  01-18-2010

Thank you kindly for this choice bit of code!  It seems like the sort of thing we might want to add to the core.

Profile
 
 
   
 
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 819, on March 11, 2010 11:15 AM
Total Registered Members: 120461 Total Logged-in Users: 37
Total Topics: 126538 Total Anonymous Users: 2
Total Replies: 665365 Total Guests: 307
Total Posts: 791903    
Members ( View Memberlist )
Newest Members:  kmotion1jelevinlizandermagnosismx2428JordanMartzShaun HardynelsonpowellLimenijetzzy