If you've worked with any kind of database-driven web application, you know that HTML forms are the foundation of the user's interaction with the database. Applications use forms to take input from the user and store it or use it to manipulate existing data. Unfortunately, HTML forms can potentially be quite tedious to write. In this article, we will look at a handful of helpful functions that Joomla! provides to save you time preparing your forms.
The JHTMLSelect class contains several methods that will assist you in creating dropdown lists and radio buttons. The method below produces a standard <select> 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);
## Create <select name="month" class="inputbox"></select> ##
$dropdown = JHTML::_('select.genericlist', $options, 'month', 'class="inputbox"', 'value', 'text', $default);
## Output created <select> list ##
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:
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:
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.