You are here: Re: [PHP] Dropdown Building Function « PHP « IT news, forums, messages
Re: [PHP] Dropdown Building Function

Posted by "Satyam" on 07/30/05 12:25

"Jack Jackson" <jackson.linux@gmail.com> wrote in message
news:42EAA938.1090209@gmail.com...
> Aaron,
> Thanks for showing me this it is very cool indeed.
>
> However maybe I am being dumb and obdurate but what I am really trying to
> do is build some of these things myself (with, thankfully, help)


Perhaps this can help. I'm sorry the doc is in Spanish, but the code is not
so large.

There are two funtions, one to load the data for a dropdown list
(CargaCombo) and the other to show it. The reason for this is that a single
combo might be used in two or more places within a web page so this allow
for reusability, plus it allows for the display of combos not generated from
the database but from a plain handcoded array, such as a list of month
names.

CargaCombo expects an SQL statement. It will assume the first field is the
key of the dropdown box. It will then concatenate every field from the
second to whichever to make the description.

MuestraCombo will display the dropdown from an array. It will assume the
key of the array to be the value attribute of the <option> tag and the value
of the array to be the description. The first parameter is the name of the
<select> tag, the third the key value of the item to be pre-selected and the
fourth an array of events for the object. This last one has to be in the
form of eventName => action.

For example:

MuestraCombo('SomeName', array(0=>'No',1=>'Yes'),1,array('onClick' =>
'doSomething();'));


Satyam



/**
* Esta funcin devuelve un array que se puede usar en {@link MuestraCombo
MuestraCombo} para mostrar un combobox.
*
* La funcin toma una instruccin de SQL y con ella arma un array donde el
primer campo que encuentra lo usa como
* clave dentro del array y los campos subsiguientes como valor. Si
hubiera ms de dos campos, concatenar los valores
* de los campos desde el segundo en adelante separndolos con barra
vertical para asignar como valor a la clave dada
* por el primer campo. Usualmente se usa con una tabla del tipo Codigo ==>
Descripcin
*
* @param string $sql Instruccin de seleccin de SQL, debe proveer al
menos dos campos.
* @return array Array con una entrada por registro obtenido, usando el
campo 0 como clave y los subsiguientes como valor
*/
function &CargaCombo($sql){
$result = mysql_query($sql) or die ('Error en la consulta: ' .
mysql_error() . "\r\n<br>$sql");
while ($line = mysql_fetch_row($result)){
$s = '';
for ($i = 1;$i < mysql_num_fields($result);$i++) $s .= ' | ' .
$line[$i];
$combo[$line[0]] = substr($s, 3);
}

return $combo;
mysql_free_result($result);
}
/**
* Emite el cdigo HTML correspondiente a un ComboBox usando el array que
se indica.
*
* El array puede haber sido obtenido mediante
* {@link CargaCombo CargaCombo}, o generado por otro medio.
* Por cada item del array emitir un <samp>&lt;option&gt;</samp> con
<samp>value</samp> igual a la clave y el texto
* a mostrar igual al valor correspondiente a esa clave.
*
* @param string $Nombre Nombre que se le dar al control
* @param array $Combo Array donde aparecen los valores a mostrar
* @param mixed $Default Clave del item que deber aparecer seleccionado
inicialmente
* @param array $Eventos Array de acciones por eventos a ser asignadas a
este control.
* El array debe estar estructurado con el nombre del evento como clave y
la accin asociada como dato.
*/

function MuestraCombo($Nombre, $Combo, $Default = null, $Eventos = null){
echo '<Select size=1 name="' , $Nombre ,'"';
if ($Eventos){
foreach($Eventos as $OnEvent => $Funcion){
echo ' ', $OnEvent, '="', $Funcion , '"';
}
}
echo '>', CRLF;

foreach ($Combo as $key => $value){
echo '<Option value="'
, htmlentities($key)
, '"';
If ($key == $Default Or (Is_Null($key) And Is_Null($Default))) echo
' selected ';
echo '>', $value , '</option>', CRLF;
}
echo '</Select>',CRLF;
}

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация