The JHTMLSelect class contains several methods that will assist you in creating dropdown lists and radio buttons. The method below produces a standard list. Notice that JHTMLSelect is actually called via the JHTML class:
## A default value -- this will be the selected item in the dropdown ##
$default = 2;
## An array of $key=>$value pairs ##
$months = array(1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr');
## Initialize array to store dropdown options ##
$options = array();
foreach($months as $key=>$value) :
## Create $value ##
$options[] = JHTML::_('select.option', $key, $value);
endforeach;
## Create ##
$dropdown = JHTML::_('select.genericlist', $options, 'month', 'class="inputbox"', 'value', 'text', $default);
## Output created list ## echo $dropdown;
That bit of code may be more trouble than it's worth for the example shown, but its advantage becomes obvious when you are dealing with a large array of values or need to populate the list with rows from the database. Now, if you would like to use radio buttons instead of a dropdown, you only need to change one line:
$radiolist = JHTML::_('select.radiolist', $options, 'month', 'class="inputbox"', 'value', 'text', $default);
JHTMLSelect also shortens a couple kinds of lists even further. If you just need a dropdown of integers (i.e., a select box of 1-12 for the months of the year), you can specify with a single line the range and incremental amount of the list.
## Pass in the start, end, and increment values ##
$integerlist = JHTML::_('select.integerlist', 1, 12, 1, 'month', 'class="inputbox"', $default);
The following line of code will produce a simple yes/no boolean radio list:
## Produce a radio list for a "published" field ##
$booleanlist = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', 'Yes', 'No');
Check out the JHTMLSelect page for more details on how you can save time and energy in creating your forms. More than likely, you will find yourself re-using these lines of code over and over in every component you create.