Histórico de 14 de diciembre de 2009

[PHP] put_select() function

Función en php para crear un menú desplegable con la etiqueta "select".

/**
 * put_select returns a string with a filled <select> html form item
 * @name the name of the form object
 * @array_values a "key, value" type array with the values for the form item
 * @marked string containing the default delected value
 * @extra string with extra data for the "select" tag, such as javascript events like "onfocus" etc.
 * @return string containing an html <select> tag
 */
function put_select($name, $array_values, $marked="", $extra="") {
	$string = "";
	// Only create the item if the values are in an array
	if (is_array($array_values)) {
		$string .= '<select name="'.$name.'" '.$extra.'>'."\n";
		$string .= '<option value="--">---</option>'."\n";
		while (list($key, $value) = each($array_values)) {
			$string .= "<option value=\"".$key."\"";
			if ($key == $marked) {
				// The default selected item
				$string .= " selected";
			}
			$string .= ">".$value."</option>\n";
		}
		$string .= "</select>\n";
	} else {
		// Return an error string
		$string .= "ax_put_select() - Error 2002";
	}
	return $string;
}

Ejemplo de uso:

include 'functions.php'; // Aquí esta la función put_select
// bla bla bla ... html form etc.
$meses = array(
	"01"=>"Enero",
	"02"=>"Febrero",
	"03"=>"Marzo",
	"04"=>"Abril",
	"05"=>"Mayo",
	"06"=>"Junio",
	"07"=>"Julio",
	"08"=>"Agosto",
	"09"=>"Septiembre",
	"10"=>"Octubre",
	"11"=>"Noviembre",
	"12"=>"Diciembre"
	);
$mes_por_defecto = date("m"); // Mes por defecto es el mes actual
print('Seleccione un mes:&nbsp;'.
	put_select("losmeses", $meses, $mes_por_defecto, "onUnFocus=\"alert('Gracias!')\";")
	.'<br/>');

Generará este código HTML:

Seleccione un mes:&nbsp;<select name="losmeses" onUnFocus="alert('Gracias!')";>
<option value="--">---</option>
<option value="01">Enero</option>
<option value="02">Febrero</option>
<option value="03">Marzo</option>
<option value="04">Abril</option>
<option value="05">Mayo</option>
<option value="06">Junio</option>
<option value="07">Julio</option>
<option value="08">Agosto</option>
<option value="09">Septiembre</option>
<option value="10">Octubre</option>
<option value="11">Noviembre</option>
<option value="12" selected>Diciembre</option>
</select>
<br/>