Create a gist now

Instantly share code, notes, and snippets.

Select menu with optgroup elements
<?php
// First you need some code to get a database result set.
// Split the resultset into two arrays, one for the product groups and one for the categories.
$sql = "SELECT id, parent_id, name, var_name FROM prod_category ORDER BY parent_id, id ASC"; $categories = mysql_query($sql);
while ($obj = mysql_fetch_object($categories)) {
if (!empty($obj->parent_id)) { // there are options
$arr_options[$obj->id]['parent'] = $obj->parent_id; // the corresponding key (group id)
$arr_options[$obj->id]['label'] = $obj->name;
$arr_options[$obj->id]['value'] = $obj->var_name;
// this array is build to check later the existings of options against the option groups
// (to create a valid select menu)
if (!in_array($obj->parent_id, $arr_check)) $arr_check[] = $obj->parent_id;
} else { // these are group elements
$arr_groups[$obj->id] = $obj->name;
}
}
function mysql_grouped_select_menu($elementName, $group_array, $option_array, $label = "", $current = "", $form_name = "myForm") {
$select = (!empty($label)) ? "<label for=\"".$elementName."\">".$label."</label>\n" : "";
$select .= "<select name=\"".$elementName."\" id=\"".$elementName."\"";
$select .= ($form_name != "") ? " onchange=\"document.".$form_name.".submit()\">\n" : ">\n";
$select .= " <option value=\"\">...</option>\n";
if (empty($_REQUEST[$elementName])) {
if ($current == "") {
$curr_val = "";
} else {
$curr_val = $current;
}
} else {
$curr_val = $_REQUEST[$elementName];
}
foreach ($group_array as $gkey => $gval) {
$select .= " <optgroup label=\"".$gval."\">\n";
foreach ($option_array as $opt_val) {
if ($opt_val['parent'] == $gkey) {
$select .= " <option value=\"".$opt_val['value']."\"";
$select .= ($opt_val['value'] == $curr_val) ? " selected=\"selected\">" : ">";
$select .= $opt_val['label']."</option>\n";
}
}
$select .= " </optgroup>\n";
}
$select .= "</select>\n";
return $select;
}
// example function call
echo "
<form action=\"\" method=\"post\" name=\"myForm\">
".mysql_grouped_select_menu("category", $arr_groups, $arr_options, "Choose a category")."
<input type=\"submit\" name=\"Submit\" value=\"OK\" />
</form>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment