2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 // +----------------------------------------------------------------------+
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1997-2003 The PHP Group |
7 // +----------------------------------------------------------------------+
8 // | This source file is subject to version 2.0 of the PHP license, |
9 // | that is bundled with this package in the file LICENSE, and is |
10 // | available at through the world-wide-web at |
11 // | http://www.php.net/license/2_02.txt. |
12 // | If you did not receive a copy of the PHP license and are unable to |
13 // | obtain it through the world-wide-web, please send a note to |
14 // | license@php.net so we can mail you a copy immediately. |
15 // +----------------------------------------------------------------------+
16 // | Authors: Adam Daniel <adaniel1@eesus.jnj.com> |
17 // | Bertrand Mansion <bmansion@mamasam.com> |
18 // +----------------------------------------------------------------------+
22 require_once('HTML/QuickForm/element.php');
25 * Class to dynamically create an HTML SELECT with all options grouped in optgroups
27 * @author Adam Daniel <adaniel1@eesus.jnj.com>
28 * @author Bertrand Mansion <bmansion@mamasam.com>
33 class MoodleQuickForm_selectgroups
extends HTML_QuickForm_element
{
37 /** add choose option */
38 var $showchoose = false;
41 * Contains the select optgroups
47 var $_optGroups = array();
50 * Default values of the SELECT
59 * html for help button, if empty then no help
64 var $_hiddenLabel=false;
69 * @param string Select name attribute
70 * @param mixed Label(s) for the select
71 * @param mixed Data to be used to populate options
72 * @param mixed An array whose keys are labels for optgroups and whose values are arrays similar to those passed
73 * to the select element with keys that are values for options and values are strings for display.
74 * @param mixed Either a typical HTML attribute string or an associative array
75 * @param bool add standard moodle "Choose..." option as first item
80 function MoodleQuickForm_selectgroups($elementName=null, $elementLabel=null, $optgrps=null, $attributes=null, $showchoose=false)
82 $this->showchoose
= $showchoose;
83 HTML_QuickForm_element
::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
84 $this->_persistantFreeze
= true;
85 $this->_type
= 'selectgroups';
86 if (isset($optgrps)) {
87 $this->loadArrayOptGroups($optgrps);
96 * Sets the default values of the select box
98 * @param mixed $values Array or comma delimited string of selected values
103 function setSelected($values)
105 if (is_string($values) && $this->getMultiple()) {
106 $values = split("[ ]?,[ ]?", $values);
108 if (is_array($values)) {
109 $this->_values
= array_values($values);
111 $this->_values
= array($values);
113 } //end func setSelected
119 * Returns an array of the selected values
123 * @return array of selected values
125 function getSelected()
127 return $this->_values
;
128 } // end func getSelected
134 * Sets the input field name
136 * @param string $name Input field name attribute
141 function setName($name)
143 $this->updateAttributes(array('name' => $name));
150 * Returns the element name
158 return $this->getAttribute('name');
162 // {{{ getPrivateName()
165 * Returns the element name (possibly with brackets appended)
171 function getPrivateName()
173 if ($this->getAttribute('multiple')) {
174 return $this->getName() . '[]';
176 return $this->getName();
178 } //end func getPrivateName
184 * Sets the value of the form element
186 * @param mixed $values Array or comma delimited string of selected values
191 function setValue($value)
193 $this->setSelected($value);
194 } // end func setValue
200 * Returns an array of the selected values
204 * @return array of selected values
208 return $this->_values
;
209 } // end func getValue
215 * Sets the select field size, only applies to 'multiple' selects
217 * @param int $size Size of select field
222 function setSize($size)
224 $this->updateAttributes(array('size' => $size));
231 * Returns the select field size
239 return $this->getAttribute('size');
246 * Sets the select mutiple attribute
248 * @param bool $multiple Whether the select supports multi-selections
253 function setMultiple($multiple)
256 $this->updateAttributes(array('multiple' => 'multiple'));
258 $this->removeAttribute('multiple');
260 } //end func setMultiple
266 * Returns the select mutiple attribute
270 * @return bool true if multiple select, false otherwise
272 function getMultiple()
274 return (bool)$this->getAttribute('multiple');
275 } //end func getMultiple
278 * Loads the options from an associative array
280 * @param array $arr Associative array of options
281 * @param mixed $values (optional) Array or comma delimited string of selected values
284 * @return PEAR_Error on error or true
287 function loadArrayOptGroups($arr, $values=null)
289 if (!is_array($arr)) {
290 return PEAR
::raiseError('Argument 1 of HTML_Select::loadArrayOptGroups is not a valid array');
292 if (isset($values)) {
293 $this->setSelected($values);
295 foreach ($arr as $key => $val) {
296 // Warning: new API since release 2.3
297 $this->addOptGroup($key, $val);
302 * Adds a new OPTION to the SELECT
304 * @param string $text Display text for the OPTION
305 * @param string $value Value for the OPTION
306 * @param mixed $attributes Either a typical HTML attribute string
307 * or an associative array
312 function addOptGroup($text, $value, $attributes=null)
314 if (null === $attributes) {
315 $attributes = array('label' => $text);
317 $attributes = $this->_parseAttributes($attributes);
318 $this->_updateAttrArray($attributes, array('label' => $text));
320 $index = count($this->_optGroups
);
321 $this->_optGroups
[$index] = array('attr' => $attributes);
322 $this->loadArrayOptions($index, $value);
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 loadArrayOptions($optgroup, $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($optgroup, $val, $key);
351 * Adds a new OPTION to an optgroup
353 * @param string $text Display text for the OPTION
354 * @param string $value Value for the OPTION
355 * @param mixed $attributes Either a typical HTML attribute string
356 * or an associative array
361 function addOption($optgroup, $text, $value, $attributes=null)
363 if (null === $attributes) {
364 $attributes = array('value' => $value);
366 $attributes = $this->_parseAttributes($attributes);
367 if (isset($attributes['selected'])) {
368 // the 'selected' attribute will be set in toHtml()
369 $this->_removeAttr('selected', $attributes);
370 if (is_null($this->_values
)) {
371 $this->_values
= array($value);
372 } elseif (!in_array($value, $this->_values
)) {
373 $this->_values
[] = $value;
376 $this->_updateAttrArray($attributes, array('value' => $value));
378 $this->_optGroups
[$optgroup]['options'][] = array('text' => $text, 'attr' => $attributes);
382 * Returns the SELECT in HTML
390 if ($this->_flagFrozen
) {
391 return $this->getFrozenHtml();
393 $tabs = $this->_getTabs();
396 if ($this->getComment() != '') {
397 $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
400 if (!$this->getMultiple()) {
401 $attrString = $this->_getAttrString($this->_attributes
);
403 $myName = $this->getName();
404 $this->setName($myName . '[]');
405 $attrString = $this->_getAttrString($this->_attributes
);
406 $this->setName($myName);
409 if ($this->_hiddenLabel
){
410 $this->_generateId();
411 $strHtml .= '<label class="accesshide" for="'.$this->getAttribute('id').'" >'.
412 $this->getLabel().'</label>';
414 $strHtml .= '<select' . $attrString . ">\n";
415 if ($this->showchoose
) {
416 $strHtml .= $tabs . "\t\t<option value=\"\">" . get_string('choose') . "...</option>\n";
418 foreach ($this->_optGroups
as $optGroup) {
419 if (empty($optGroup['options'])) {
423 $strHtml .= $tabs . "\t<optgroup" . ($this->_getAttrString($optGroup['attr'])) . '>';
424 foreach ($optGroup['options'] as $option){
425 if (is_array($this->_values
) && in_array((string)$option['attr']['value'], $this->_values
)) {
426 $this->_updateAttrArray($option['attr'], array('selected' => 'selected'));
428 $strHtml .= $tabs . "\t\t<option" . $this->_getAttrString($option['attr']) . '>' .
429 $option['text'] . "</option>\n";
431 $strHtml .= $tabs . "\t</optgroup>\n";
433 return $strHtml . $tabs . '</select>';
438 // {{{ getFrozenHtml()
441 * Returns the value of field without HTML tags
447 function getFrozenHtml()
450 if (is_array($this->_values
)) {
451 foreach ($this->_values
as $key => $val) {
452 foreach ($this->_optGroups
as $optGroup) {
453 for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++
) {
454 if ((string)$val == (string)$optGroup['options'][$i]['attr']['value']) {
455 $value[$key] = $optGroup['options'][$i]['text'];
462 $html = empty($value)?
' ': join('<br />', $value);
463 if ($this->_persistantFreeze
) {
464 $name = $this->getPrivateName();
465 // Only use id attribute if doing single hidden input
466 if (1 == count($value)) {
467 $id = $this->getAttribute('id');
468 $idAttr = isset($id)?
array('id' => $id): array();
472 foreach ($value as $key => $item) {
473 $html .= '<input' . $this->_getAttrString(array(
476 'value' => $this->_values
[$key]
477 ) +
$idAttr) . ' />';
481 } //end func getFrozenHtml
487 * We check the options and return only the values that _could_ have been
488 * selected. We also return a scalar value if select is not "multiple"
490 function exportValue(&$submitValues, $assoc = false)
492 $value = $this->_findValue($submitValues);
493 if (is_null($value)) {
494 $value = $this->getValue();
495 } elseif(!is_array($value)) {
496 $value = array($value);
498 if (is_array($value) && !empty($this->_optGroups
)) {
500 foreach ($value as $v) {
501 foreach ($this->_optGroups
as $optGroup){
502 if (empty($optGroup['options'])) {
505 for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++
) {
506 if ($v == $optGroup['options'][$i]['attr']['value']) {
514 $cleanValue = $value;
516 if (is_array($cleanValue) && !$this->getMultiple()) {
517 return $this->_prepareValue($cleanValue[0], $assoc);
519 return $this->_prepareValue($cleanValue, $assoc);
524 // {{{ onQuickFormEvent()
526 function onQuickFormEvent($event, $arg, &$caller)
528 if ('updateValue' == $event) {
529 $value = $this->_findValue($caller->_constantValues
);
530 if (null === $value) {
531 $value = $this->_findValue($caller->_submitValues
);
532 // Fix for bug #4465 & #5269
533 // XXX: should we push this to element::onQuickFormEvent()?
534 if (null === $value && (!$caller->isSubmitted() ||
!$this->getMultiple())) {
535 $value = $this->_findValue($caller->_defaultValues
);
538 if (null !== $value) {
539 $this->setValue($value);
543 return parent
::onQuickFormEvent($event, $arg, $caller);
546 function setHiddenLabel($hiddenLabel){
547 $this->_hiddenLabel
= $hiddenLabel;
550 * Automatically generates and assigns an 'id' attribute for the element.
552 * Currently used to ensure that labels work on radio buttons and
553 * checkboxes. Per idea of Alexander Radivanovich.
554 * Overriden in moodleforms to remove qf_ prefix.
559 function _generateId()
563 if (!$this->getAttribute('id')) {
564 $this->updateAttributes(array('id' => 'id_'. substr(md5(microtime() . $idx++
), 0, 6)));
566 } // end func _generateId
568 * set html for help button
571 * @param array $help array of arguments to make a help button
572 * @param string $function function name to call to get html
574 function setHelpButton($helpbuttonargs, $function='helpbutton'){
575 if (!is_array($helpbuttonargs)){
576 $helpbuttonargs=array($helpbuttonargs);
578 $helpbuttonargs=$helpbuttonargs;
580 //we do this to to return html instead of printing it
581 //without having to specify it in every call to make a button.
582 if ('helpbutton' == $function){
583 $defaultargs=array('', '', 'moodle', true, false, '', true);
584 $helpbuttonargs=$helpbuttonargs +
$defaultargs ;
586 $this->_helpbutton
=call_user_func_array($function, $helpbuttonargs);
589 * get html for help button
592 * @return string html for help button
594 function getHelpButton(){
595 return $this->_helpbutton
;
599 * Slightly different container template when frozen. Don't want to use a label tag
600 * with a for attribute in that case for the element label but instead use a div.
601 * Templates are defined in renderer constructor.
605 function getElementTemplateType(){
606 if ($this->_flagFrozen
){