2 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
5 * Class to dynamically create an HTML SELECT
9 * LICENSE: This source file is subject to version 3.01 of the PHP license
10 * that is available through the world-wide-web at the following URI:
11 * http://www.php.net/license/3_01.txt If you did not receive a copy of
12 * the PHP License and are unable to obtain it through the web, please
13 * send a note to license@php.net so we can mail you a copy immediately.
16 * @package HTML_QuickForm
17 * @author Adam Daniel <adaniel1@eesus.jnj.com>
18 * @author Bertrand Mansion <bmansion@mamasam.com>
19 * @author Alexey Borzov <avb@php.net>
20 * @copyright 2001-2011 The PHP Group
21 * @license http://www.php.net/license/3_01.txt PHP License 3.01
23 * @link http://pear.php.net/package/HTML_QuickForm
27 * Base class for form elements
29 require_once 'HTML/QuickForm/element.php';
32 * Class to dynamically create an HTML SELECT
35 * @package HTML_QuickForm
36 * @author Adam Daniel <adaniel1@eesus.jnj.com>
37 * @author Bertrand Mansion <bmansion@mamasam.com>
38 * @author Alexey Borzov <avb@php.net>
39 * @version Release: 3.2.16
42 class HTML_QuickForm_select extends HTML_QuickForm_element {
47 * Contains the select options
53 var $_options = array();
56 * Default values of the SELECT
70 * @param string Select name attribute
71 * @param mixed Label(s) for the select
72 * @param mixed Data to be used to populate options
73 * @param mixed Either a typical HTML attribute string or an associative array
78 function HTML_QuickForm_select($elementName=null, $elementLabel=null, $options=null, $attributes=null)
80 HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
81 $this->_persistantFreeze = true;
82 $this->_type = 'select';
83 if (isset($options)) {
84 $this->load($options);
92 * Returns the current API version
101 } //end func apiVersion
107 * Sets the default values of the select box
109 * @param mixed $values Array or comma delimited string of selected values
114 function setSelected($values)
116 if (is_string($values) && $this->getMultiple()) {
117 $values = preg_split("/[ ]?,[ ]?/", $values);
119 if (is_array($values)) {
120 $this->_values = array_values($values);
122 $this->_values = array($values);
124 } //end func setSelected
130 * Returns an array of the selected values
134 * @return array of selected values
136 function getSelected()
138 return $this->_values;
139 } // end func getSelected
145 * Sets the input field name
147 * @param string $name Input field name attribute
152 function setName($name)
154 $this->updateAttributes(array('name' => $name));
161 * Returns the element name
169 return $this->getAttribute('name');
173 // {{{ getPrivateName()
176 * Returns the element name (possibly with brackets appended)
182 function getPrivateName()
184 if ($this->getAttribute('multiple')) {
185 return $this->getName() . '[]';
187 return $this->getName();
189 } //end func getPrivateName
195 * Sets the value of the form element
197 * @param mixed $values Array or comma delimited string of selected values
202 function setValue($value)
204 $this->setSelected($value);
205 } // end func setValue
211 * Returns an array of the selected values
215 * @return array of selected values
219 return $this->_values;
220 } // end func getValue
226 * Sets the select field size, only applies to 'multiple' selects
228 * @param int $size Size of select field
233 function setSize($size)
235 $this->updateAttributes(array('size' => $size));
242 * Returns the select field size
250 return $this->getAttribute('size');
257 * Sets the select mutiple attribute
259 * @param bool $multiple Whether the select supports multi-selections
264 function setMultiple($multiple)
267 $this->updateAttributes(array('multiple' => 'multiple'));
269 $this->removeAttribute('multiple');
271 } //end func setMultiple
277 * Returns the select mutiple attribute
281 * @return bool true if multiple select, false otherwise
283 function getMultiple()
285 return (bool)$this->getAttribute('multiple');
286 } //end func getMultiple
292 * Adds a new OPTION to the SELECT
294 * @param string $text Display text for the OPTION
295 * @param string $value Value for the OPTION
296 * @param mixed $attributes Either a typical HTML attribute string
297 * or an associative array
302 function addOption($text, $value, $attributes=null)
304 if (null === $attributes) {
305 $attributes = array('value' => (string)$value);
307 $attributes = $this->_parseAttributes($attributes);
308 if (isset($attributes['selected'])) {
309 // the 'selected' attribute will be set in toHtml()
310 $this->_removeAttr('selected', $attributes);
311 if (is_null($this->_values)) {
312 $this->_values = array($value);
313 } elseif (!in_array($value, $this->_values)) {
314 $this->_values[] = $value;
317 $this->_updateAttrArray($attributes, array('value' => (string)$value));
319 $this->_options[] = array('text' => $text, 'attr' => $attributes);
320 } // end func addOption
326 * Loads the options from an associative array
328 * @param array $arr Associative array of options
329 * @param mixed $values (optional) Array or comma delimited string of selected values
332 * @return PEAR_Error on error or true
335 function loadArray($arr, $values=null)
337 if (!is_array($arr)) {
338 return PEAR::raiseError('Argument 1 of HTML_Select::loadArray is not a valid array');
340 if (isset($values)) {
341 $this->setSelected($values);
343 foreach ($arr as $key => $val) {
344 // Warning: new API since release 2.3
345 $this->addOption($val, $key);
348 } // end func loadArray
351 // {{{ loadDbResult()
354 * Loads the options from DB_result object
356 * If no column names are specified the first two columns of the result are
357 * used as the text and value columns respectively
358 * @param object $result DB_result object
359 * @param string $textCol (optional) Name of column to display as the OPTION text
360 * @param string $valueCol (optional) Name of column to use as the OPTION value
361 * @param mixed $values (optional) Array or comma delimited string of selected values
364 * @return PEAR_Error on error or true
367 function loadDbResult(&$result, $textCol=null, $valueCol=null, $values=null)
369 if (!is_object($result) || !is_a($result, 'db_result')) {
370 return PEAR::raiseError('Argument 1 of HTML_Select::loadDbResult is not a valid DB_result');
372 if (isset($values)) {
373 $this->setValue($values);
375 $fetchMode = ($textCol && $valueCol) ? DB_FETCHMODE_ASSOC : DB_FETCHMODE_ORDERED;
376 while (is_array($row = $result->fetchRow($fetchMode)) ) {
377 if ($fetchMode == DB_FETCHMODE_ASSOC) {
378 $this->addOption($row[$textCol], $row[$valueCol]);
380 $this->addOption($row[0], $row[1]);
384 } // end func loadDbResult
390 * Queries a database and loads the options from the results
392 * @param mixed $conn Either an existing DB connection or a valid dsn
393 * @param string $sql SQL query string
394 * @param string $textCol (optional) Name of column to display as the OPTION text
395 * @param string $valueCol (optional) Name of column to use as the OPTION value
396 * @param mixed $values (optional) Array or comma delimited string of selected values
402 function loadQuery(&$conn, $sql, $textCol=null, $valueCol=null, $values=null)
404 if (is_string($conn)) {
405 require_once('DB.php');
406 $dbConn = &DB::connect($conn, true);
407 if (DB::isError($dbConn)) {
410 } elseif (is_subclass_of($conn, "db_common")) {
413 return PEAR::raiseError('Argument 1 of HTML_Select::loadQuery is not a valid type');
415 $result = $dbConn->query($sql);
416 if (DB::isError($result)) {
419 $this->loadDbResult($result, $textCol, $valueCol, $values);
421 if (is_string($conn)) {
422 $dbConn->disconnect();
425 } // end func loadQuery
431 * Loads options from different types of data sources
433 * This method is a simulated overloaded method. The arguments, other than the
434 * first are optional and only mean something depending on the type of the first argument.
435 * If the first argument is an array then all arguments are passed in order to loadArray.
436 * If the first argument is a db_result then all arguments are passed in order to loadDbResult.
437 * If the first argument is a string or a DB connection then all arguments are
438 * passed in order to loadQuery.
439 * @param mixed $options Options source currently supports assoc array or DB_result
440 * @param mixed $param1 (optional) See function detail
441 * @param mixed $param2 (optional) See function detail
442 * @param mixed $param3 (optional) See function detail
443 * @param mixed $param4 (optional) See function detail
446 * @return PEAR_Error on error or true
449 function load(&$options, $param1=null, $param2=null, $param3=null, $param4=null)
452 case is_array($options):
453 return $this->loadArray($options, $param1);
455 case (is_a($options, 'db_result')):
456 return $this->loadDbResult($options, $param1, $param2, $param3);
458 case (is_string($options) && !empty($options) || is_subclass_of($options, "db_common")):
459 return $this->loadQuery($options, $param1, $param2, $param3, $param4);
468 * Returns the SELECT in HTML
476 if ($this->_flagFrozen) {
477 return $this->getFrozenHtml();
479 $tabs = $this->_getTabs();
482 if ($this->getComment() != '') {
483 $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
486 if (!$this->getMultiple()) {
487 $attrString = $this->_getAttrString($this->_attributes);
489 $myName = $this->getName();
490 $this->setName($myName . '[]');
491 $attrString = $this->_getAttrString($this->_attributes);
492 $this->setName($myName);
494 $strHtml .= $tabs . '<select' . $attrString . ">\n";
496 $strValues = is_array($this->_values)? array_map('strval', $this->_values): array();
497 foreach ($this->_options as $option) {
498 if (!empty($strValues) && in_array($option['attr']['value'], $strValues, true)) {
499 $option['attr']['selected'] = 'selected';
501 $strHtml .= $tabs . "\t<option" . $this->_getAttrString($option['attr']) . '>' .
502 $option['text'] . "</option>\n";
505 return $strHtml . $tabs . '</select>';
510 // {{{ getFrozenHtml()
513 * Returns the value of field without HTML tags
519 function getFrozenHtml()
522 if (is_array($this->_values)) {
523 foreach ($this->_values as $key => $val) {
524 for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
525 if (0 == strcmp($val, $this->_options[$i]['attr']['value'])) {
526 $value[$key] = $this->_options[$i]['text'];
532 $html = empty($value)? ' ': join('<br />', $value);
533 if ($this->_persistantFreeze) {
534 $name = $this->getPrivateName();
535 // Only use id attribute if doing single hidden input
536 if (1 == count($value)) {
537 $id = $this->getAttribute('id');
538 $idAttr = isset($id)? array('id' => $id): array();
542 foreach ($value as $key => $item) {
543 $html .= '<input' . $this->_getAttrString(array(
546 'value' => $this->_values[$key]
547 ) + $idAttr) . ' />';
551 } //end func getFrozenHtml
557 * We check the options and return only the values that _could_ have been
558 * selected. We also return a scalar value if select is not "multiple"
560 function exportValue(&$submitValues, $assoc = false)
562 $value = $this->_findValue($submitValues);
563 if (is_null($value)) {
564 $value = $this->getValue();
565 } elseif(!is_array($value)) {
566 $value = array($value);
568 if (is_array($value) && !empty($this->_options)) {
570 foreach ($value as $v) {
571 for ($i = 0, $optCount = count($this->_options); $i < $optCount; $i++) {
572 if (0 == strcmp($v, $this->_options[$i]['attr']['value'])) {
579 $cleanValue = $value;
581 if (is_array($cleanValue) && !$this->getMultiple()) {
582 return $this->_prepareValue($cleanValue[0], $assoc);
584 return $this->_prepareValue($cleanValue, $assoc);
589 // {{{ onQuickFormEvent()
591 function onQuickFormEvent($event, $arg, &$caller)
593 if ('updateValue' == $event) {
594 $value = $this->_findValue($caller->_constantValues);
595 if (null === $value) {
596 $value = $this->_findValue($caller->_submitValues);
597 // Fix for bug #4465 & #5269
598 // XXX: should we push this to element::onQuickFormEvent()?
599 if (null === $value && (!$caller->isSubmitted() || !$this->getMultiple())) {
600 $value = $this->_findValue($caller->_defaultValues);
603 if (null !== $value) {
604 $this->setValue($value);
608 return parent::onQuickFormEvent($event, $arg, $caller);
613 } //end class HTML_QuickForm_select