blog.calebnance.com

It's So Loud, Inside My Head...

Thursday, 20 October 2011 10:20

How To Create A United States Select Box In Joomla

Written by  Caleb Nance

First we want to have the array of States in our code. See Below.

$states = array("AK","AL","AR","AZ","CA","CO","CT","DC","DE","FL","GA","HI","IA","ID",
"IL","IN","KS","KY","LA","MA","MD","ME","MI","MN","MO","MS","MT","NC","ND","NE","NH",
"NJ","NM","NV","NY","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VA","VT","WA",
"WI","WV","WY");

Then you want to create the list (select list options). Above is the simplest way of creating a state array, but right now the key of each array is 0, 1, 2. This is not what we want, we want the key and value of the array to be the same. So this next line fixes just that.

$s = 0;
foreach($states as $state):
$list[$s]->id = $state;
$list[$s]->name = $state;
$s++;
endforeach;

Now we have the list like we need it to be. Now on to the creating of the select list!

$default	= 'NC';
$field = 'state';

$options = array();
foreach($list as $value):
$options[] = JHTML::_('select.option', $value->id, $value->name);
endforeach;

$select = JHTML::_('select.genericlist', $options, $field,
'class="inputbox"', 'value', 'text', $default);

As you see above, a variable for $default and $field. This is more if you want to set this in a function and have those variables passed into that function. I do it that way and it is the best way to go about using this, just create a creatSelect() function in your Model or Controller and you are good to go for the whole component! Saves lots of time, and only needs to be written once.

I set up the function to require 3 variables ($list, $default, $field).

Last modified on Thursday, 20 October 2011 10:40
blog comments powered by Disqus