Using Optgroup in a Selectbox

To give your user a better browsing experience, you could use so called ‘optgroups’ to seperate groups of options in a select list for your forms. The optgroup element is defined by w3.org as “[it] allows authors to group choices logically. This is particularly helpful when the user must choose from a long list of options; groups of related choices are easier to grasp and remember than a single long list of options.”.

A Dirty Hack in Joomla 1.5

Adding an optgroup to a select element in Joomla that uses valid (X)HTML code requires you to use a hack. The code below (found in libraries/joomla/html/html/select.php) is used when you try to use an optgroup. Especially the comment above the if statement worries me…

// This is real dirty, open to suggestions,
// barring doing a propper object to handle it
if ($k === '') {
 $html .= '';
}

To add an optgroup to your select element on Joomla 1.5, you can use the following code:

// Define arrays filled with test data; would normally come from your database
$cars = array('Ferrari', 'Bugatti', 'Porsche');
$babes = array('Megan Fox', 'Alyssa Milano', 'Doutzen Kroes');

// Create an empty array to be filled with options
$options = array();

// Create the initial option
$options[] = JHTML :: _('select.option', '', '- What do you like most -');

// Open our 'Cars' optgroup
$options[] = JHTML::_('select.optgroup', 'Cars');

// Loop through the 'Cars' data
foreach($cars as $key => $text) {
 // Create each option tag within this optgroup
 $options[] = JHTML::_('select.option', $key, $text);
}

// Use the hack below to close the optgroup
$options[] = JHTML::_('select.option', '');

// Now open our 'Babes' optgroup
$options[] = JHTML::_('select.optgroup', 'Babes');

// Loop through the 'Babes' data this time
foreach($babes as $key => $text) {
 // Create each option tag within this optgroup
 $options[] = JHTML::_('select.option', $key, $text);
}

// Use the hack below to close this last optgroup
$options[] = JHTML::_('select.option', '');

// Generate the select element with our parameters
$select = JHTML::_(
 'select.genericlist', // Because we are creating a 'select' element
 $options,             // The options we created above
 'select_name',        // The name your select element should have in your HTML 
 'size="1" ',          // Extra parameters to add to your element
 'value',              // The name of the object variable for the option value
 'text',               // The name of the object variable for the option text
 'selected_key',       // The key that is selected (accepts an array or a string)
 false                 // Translate the option results?
);
 
// Display our select box
echo $select;

Joomla 1.6

In Joomla 1.6 the problem seems resolved by the adding the groupedlist method. We can’t wait until the stable release of Joomla 1.6 as it seems to resolve many more problems we’re encountering lately!

Comments are currently closed.