Dynamic Select boxes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Dynamic Select boxes

Post by hawleyjr »

In regards to timvw's post. He uses the following code to populate a HTML select box.

Code: Select all

<?php
function state_dropdown()
{
    $options = "";
    $state = $_SESSION['state'];
    $query = "SELECT abbrev, IF(abbrev = '$state', ' SELECTED', '') AS selected FROM states";
    db_connect();
    $result = mysql_query($query);
    while ($row = mysql_fetch_assoc($result))
    {
        $options .= "<option{$row['selected']}>{$row['abbrev']}</option>";
    }
    db_close();
    echo $options;   
}
?>
Kudos Timvw I think that’s a pretty cool way to do it. Now my question is: Is that the right way to do it? We all know there are a thousand ways to skin a cat and typically it comes down to the preferences of the programmer. I like to get my data from the DB and make PHP do the entire decision making. I wrote a function a while back to handle select boxes. It is kind of sloppy but it does the job.

Code: Select all

<?php
/* THIS FUNCTION WILL ECHO OUT THE HTML NEEDED FOR A HTML LIST BOX 
	IF $A_OPTIONVALUES IS NULL USE DISPLAY VALUES ARRAY KEY
	IF $ECHOHTML IS TRUE ECHO HTML ELSE RETURN HTML
	IF $use_dsp_val_as_key USE $a_displayValues AS VALUE AND DISPLAY
	$selected_option_value CAN BE AN ARRAY FOR MULTIPLE SELECTION BOXES
*/

function printSelectBoxOptions($a_displayValues, $a_optionValues, $selected_option_value,$echoHTML,$use_dsp_val_as_key){
	
	//echo '<PRE>'; print_r(func_get_args()); echo '</PRE>';
	$html = '';
	
	$arrayCount = 0;
	
	//IF OPTION VALUES IS NULL USE DISPLAY VALUE OR ARRAY KEY FOR OPTION VALUE
	if(is_null($a_optionValues)){
		if($use_dsp_val_as_key)//USE DISPLAY AS OPTION VALUE
			$a_optionValues = &$a_displayValues;
		else //USE DISPLAY ARRAY KEY AS OPTION VALUE
			$a_optionValues = array_keys($a_displayValues);
	}
	if(is_array($a_displayValues)){
		foreach ($a_displayValues as $x => $v) {
			
			//IF SELECTED OPTION VALUE IS AN ARRAY
			//SEARCH ARRAY FOR VALUE
			//THIS IS USED FOR MULTIPLE SELECT BOXES
			$is_sel = FALSE;
			if(is_array($selected_option_value)){
				$is_sel = search_array_forValue($a_optionValues[$arrayCount], $selected_option_value);
			}
			
			if($is_sel or $a_optionValues[$arrayCount]==$selected_option_value)
				$sel = ' selected';
			else
				$sel = '';
			
			$html.= '<option value="'.$a_optionValues[$arrayCount].'"'.$sel.'>'.$a_displayValues[$x].'</option>'."\r";
			$arrayCount++;
	
		}
	}else{
		return FALSE;
	}
	if($echoHTML){
		echo $html;
		return TRUE;
	}else{
		return $html;
	}

}
?>
One of the reasons I like this is because I can quickly create select boxes:

Code: Select all

<?php

//CREATE SELECT BOX WITH 1 - 100
//MAKE 22 THE SELECTED VALUE

echo '<select>';
printSelectBoxOptions(range(0, 100), NULL, 22,TRUE,TRUE);
echo '</select>';


?>
In the example above I would have done something like this:

Code: Select all

<?php
$a_states= array();
$state = &$_SESSION['state'];
$query = "SELECT abbrev FROM states";
db_connect();
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$a_states[] = $row['abbrev'];
}
db_close();

echo '<select>';
printSelectBoxOptions($a_states, $a_states, $state,TRUE,FALSE);
echo '</select>';

?>
The posting by timvw just sparked my interest to see how others handle select boxes.
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

heres how i do it


you dont have to use sessions, its just a demo.
you need to feed it an associate array, but that could easily be modified.

you can just cut and paste this whole thing and it will work if you wanna try it

Code: Select all

<?php


function makeSelectMenu($menuName, $options, $chosen) {
    $list = '';
    foreach ($options as $option => $text) {
        $selected = ($chosen === $option) ? ' selected="selected"' : '';
        $list .= " <option value="$option"$selected>$text</option>\n";
    }
    return "\n<select name="$menuName" id="$menuName">\n$list</select>\n";
}


// example usage

session_start();


// here we define the option names, and the corresponding text to be displayed for that option
$options = array(
    'red' => 'I like Red',
    'blue' => 'I like Blue',
    'green' => 'I like Green'
  );

// this will be the name="" value in the html select list
$menuName = 'favoriteColor';




if (isSet($_POST[$menuName])) {
    $_SESSION[$menuName] = $_POST[$menuName];
}




// $chosen will obviously be filled with the users choice 
if (isSet($_SESSION[$menuName])) {
    $chosen = $_SESSION[$menuName];
} else {
    $chosen = '';
}


$selectMenu = makeSelectMenu($menuName, $options, $chosen);



/*
this above example will output the following:

<select name="favoriteColor" id="favoriteColor">
<option value="red">I like Red</option>
<option value="blue">I like Blue</option>
<option value="green">I like Green</option>
</select>

and if the user selects "green", this would be the output

<select name="favoriteColor" id="favoriteColor">
<option value="red">I like Red</option>
<option value="blue">I like Blue</option>
<option value="green" selected="selected">I like Green</option>
</select>





HERES HOW SMALL THE CODE IS w/out comments:

$options = array(
    '' => 'Choose Your Favorite Color',
    'red' => 'I like Red',
    'blue' => 'I like Blue',
    'green' => 'I like Green'
  );
$menuName = 'favoriteColor';
$chosen = '';
if (isSet($_POST[$menuName])) $_SESSION[$menuName] = $_POST[$menuName];
if (isSet($_SESSION[$menuName])) $chosen = $_SESSION[$menuName];
$selectMenu = makeSelectMenu($menuName, $options, $chosen);








*/

?>
<html>
<form method="post">

<?php echo $selectMenu; ?>
<input type="submit" />
</form>


</html>
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

it is not ideal, because it depends on data from a mysql database, and therefore is absolutely not flexible. i guess it is not clear that that code is my way of doing select boxes ;)

i usually first retrieve all the needed data (model), then wrap it in some xml (controller) and then do some xsl tranformation (view).

anyway, you might want to have a look at http://www.phpcomplete.com/archives/200 ... one-right/ which is something nice too ;)
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

timvw wrote:anyway, you might want to have a look at http://www.phpcomplete.com/archives/200 ... one-right/ which is something nice too ;)
This may not be the right forum, but... that is the most non-standard approach I've seen. I know, just as everyone else knows how cumbersome the CTRL-Click selection process is. However, to develop your own GUI form field is probably not the best choice. How can we expect the world (WWW) to intuitively use our tools if we are making our own DOM. This is like the typical Microsoft approach to the situation at hand. If life isn’t going my way, make my own standard. Which is why Windows and Office is such a cluster, or why CSS and IE is a joke…Anyway, sorry to gripe; I just have issues with stuff like this.
Post Reply