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 // +----------------------------------------------------------------------+
20 require_once('HTML/QuickForm/element.php');
23 * Class to dynamically create an HTML SELECT with all options grouped in optgroups
25 * @author Adam Daniel <adaniel1@eesus.jnj.com>
26 * @author Bertrand Mansion <bmansion@mamasam.com>
31 class MoodleQuickForm_selectgroups
extends HTML_QuickForm_element
{
35 /** add choose option */
36 var $showchoose = false;
39 * Contains the select optgroups
45 var $_optGroups = array();
48 * Default values of the SELECT
57 * html for help button, if empty then no help
62 var $_hiddenLabel=false;
67 * @param string Select name attribute
68 * @param mixed Label(s) for the select
69 * @param mixed Data to be used to populate options
70 * @param mixed An array whose keys are labels for optgroups and whose values are arrays similar to those passed
71 * to the select element with keys that are values for options and values are strings for display.
72 * @param mixed Either a typical HTML attribute string or an associative array
73 * @param bool add standard moodle "Choose..." option as first item
78 function MoodleQuickForm_selectgroups($elementName=null, $elementLabel=null, $optgrps=null, $attributes=null, $showchoose=false)
80 $this->showchoose
= $showchoose;
81 HTML_QuickForm_element
::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
82 $this->_persistantFreeze
= true;
83 $this->_type
= 'selectgroups';
84 if (isset($optgrps)) {
85 $this->loadArrayOptGroups($optgrps);
94 * Sets the default values of the select box
96 * @param mixed $values Array or comma delimited string of selected values
101 function setSelected($values)
103 if (is_string($values) && $this->getMultiple()) {
104 $values = preg_split("/[ ]?,[ ]?/", $values);
106 if (is_array($values)) {
107 $this->_values
= array_values($values);
109 $this->_values
= array($values);
111 } //end func setSelected
117 * Returns an array of the selected values
121 * @return array of selected values
123 function getSelected()
125 return $this->_values
;
126 } // end func getSelected
132 * Sets the input field name
134 * @param string $name Input field name attribute
139 function setName($name)
141 $this->updateAttributes(array('name' => $name));
148 * Returns the element name
156 return $this->getAttribute('name');
160 // {{{ getPrivateName()
163 * Returns the element name (possibly with brackets appended)
169 function getPrivateName()
171 if ($this->getAttribute('multiple')) {
172 return $this->getName() . '[]';
174 return $this->getName();
176 } //end func getPrivateName
182 * Sets the value of the form element
184 * @param mixed $values Array or comma delimited string of selected values
189 function setValue($value)
191 $this->setSelected($value);
192 } // end func setValue
198 * Returns an array of the selected values
202 * @return array of selected values
206 return $this->_values
;
207 } // end func getValue
213 * Sets the select field size, only applies to 'multiple' selects
215 * @param int $size Size of select field
220 function setSize($size)
222 $this->updateAttributes(array('size' => $size));
229 * Returns the select field size
237 return $this->getAttribute('size');
244 * Sets the select mutiple attribute
246 * @param bool $multiple Whether the select supports multi-selections
251 function setMultiple($multiple)
254 $this->updateAttributes(array('multiple' => 'multiple'));
256 $this->removeAttribute('multiple');
258 } //end func setMultiple
264 * Returns the select mutiple attribute
268 * @return bool true if multiple select, false otherwise
270 function getMultiple()
272 return (bool)$this->getAttribute('multiple');
273 } //end func getMultiple
276 * Loads the options from an associative array
278 * @param array $arr Associative array of options
279 * @param mixed $values (optional) Array or comma delimited string of selected values
282 * @return PEAR_Error on error or true
285 function loadArrayOptGroups($arr, $values=null)
287 if (!is_array($arr)) {
288 return PEAR
::raiseError('Argument 1 of HTML_Select::loadArrayOptGroups is not a valid array');
290 if (isset($values)) {
291 $this->setSelected($values);
293 foreach ($arr as $key => $val) {
294 // Warning: new API since release 2.3
295 $this->addOptGroup($key, $val);
300 * Adds a new OPTION to the SELECT
302 * @param string $text Display text for the OPTION
303 * @param string $value Value for the OPTION
304 * @param mixed $attributes Either a typical HTML attribute string
305 * or an associative array
310 function addOptGroup($text, $value, $attributes=null)
312 if (null === $attributes) {
313 $attributes = array('label' => $text);
315 $attributes = $this->_parseAttributes($attributes);
316 $this->_updateAttrArray($attributes, array('label' => $text));
318 $index = count($this->_optGroups
);
319 $this->_optGroups
[$index] = array('attr' => $attributes);
320 $this->loadArrayOptions($index, $value);
324 * Loads the options from an associative array
326 * @param array $arr Associative array of options
327 * @param mixed $values (optional) Array or comma delimited string of selected values
330 * @return PEAR_Error on error or true
333 function loadArrayOptions($optgroup, $arr, $values=null)
335 if (!is_array($arr)) {
336 return PEAR
::raiseError('Argument 1 of HTML_Select::loadArray is not a valid array');
338 if (isset($values)) {
339 $this->setSelected($values);
341 foreach ($arr as $key => $val) {
342 // Warning: new API since release 2.3
343 $this->addOption($optgroup, $val, $key);
349 * Adds a new OPTION to an optgroup
351 * @param string $text Display text for the OPTION
352 * @param string $value Value for the OPTION
353 * @param mixed $attributes Either a typical HTML attribute string
354 * or an associative array
359 function addOption($optgroup, $text, $value, $attributes=null)
361 if (null === $attributes) {
362 $attributes = array('value' => $value);
364 $attributes = $this->_parseAttributes($attributes);
365 if (isset($attributes['selected'])) {
366 // the 'selected' attribute will be set in toHtml()
367 $this->_removeAttr('selected', $attributes);
368 if (is_null($this->_values
)) {
369 $this->_values
= array($value);
370 } elseif (!in_array($value, $this->_values
)) {
371 $this->_values
[] = $value;
374 $this->_updateAttrArray($attributes, array('value' => $value));
376 $this->_optGroups
[$optgroup]['options'][] = array('text' => $text, 'attr' => $attributes);
380 * Returns the SELECT in HTML
388 if ($this->_flagFrozen
) {
389 return $this->getFrozenHtml();
391 $tabs = $this->_getTabs();
394 if ($this->getComment() != '') {
395 $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
398 if (!$this->getMultiple()) {
399 $attrString = $this->_getAttrString($this->_attributes
);
401 $myName = $this->getName();
402 $this->setName($myName . '[]');
403 $attrString = $this->_getAttrString($this->_attributes
);
404 $this->setName($myName);
407 if ($this->_hiddenLabel
){
408 $this->_generateId();
409 $strHtml .= '<label class="accesshide" for="'.$this->getAttribute('id').'" >'.
410 $this->getLabel().'</label>';
412 $strHtml .= '<select' . $attrString . ">\n";
413 if ($this->showchoose
) {
414 $strHtml .= $tabs . "\t\t<option value=\"\">" . get_string('choose') . "...</option>\n";
416 foreach ($this->_optGroups
as $optGroup) {
417 if (empty($optGroup['options'])) {
421 $strHtml .= $tabs . "\t<optgroup" . ($this->_getAttrString($optGroup['attr'])) . '>';
422 foreach ($optGroup['options'] as $option){
423 if (is_array($this->_values
) && in_array((string)$option['attr']['value'], $this->_values
)) {
424 $this->_updateAttrArray($option['attr'], array('selected' => 'selected'));
426 $strHtml .= $tabs . "\t\t<option" . $this->_getAttrString($option['attr']) . '>' .
427 $option['text'] . "</option>\n";
429 $strHtml .= $tabs . "\t</optgroup>\n";
431 return $strHtml . $tabs . '</select>';
436 // {{{ getFrozenHtml()
439 * Returns the value of field without HTML tags
445 function getFrozenHtml()
448 if (is_array($this->_values
)) {
449 foreach ($this->_values
as $key => $val) {
450 foreach ($this->_optGroups
as $optGroup) {
451 for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++
) {
452 if ((string)$val == (string)$optGroup['options'][$i]['attr']['value']) {
453 $value[$key] = $optGroup['options'][$i]['text'];
460 $html = empty($value)?
' ': join('<br />', $value);
461 if ($this->_persistantFreeze
) {
462 $name = $this->getPrivateName();
463 // Only use id attribute if doing single hidden input
464 if (1 == count($value)) {
465 $id = $this->getAttribute('id');
466 $idAttr = isset($id)?
array('id' => $id): array();
470 foreach ($value as $key => $item) {
471 $html .= '<input' . $this->_getAttrString(array(
474 'value' => $this->_values
[$key]
475 ) +
$idAttr) . ' />';
479 } //end func getFrozenHtml
485 * We check the options and return only the values that _could_ have been
486 * selected. We also return a scalar value if select is not "multiple"
488 function exportValue(&$submitValues, $assoc = false)
490 if (empty($this->_optGroups
)) {
491 return $this->_prepareValue(null, $assoc);
494 $value = $this->_findValue($submitValues);
495 if (is_null($value)) {
496 $value = $this->getValue();
498 $value = (array)$value;
501 foreach ($value as $v) {
502 foreach ($this->_optGroups
as $optGroup){
503 if (empty($optGroup['options'])) {
506 foreach ($optGroup['options'] as $option) {
507 if ((string)$option['attr']['value'] === (string)$v) {
508 $cleaned[] = (string)$option['attr']['value'];
515 if (empty($cleaned)) {
516 return $this->_prepareValue(null, $assoc);
518 if ($this->getMultiple()) {
519 return $this->_prepareValue($cleaned, $assoc);
521 return $this->_prepareValue($cleaned[0], $assoc);
526 // {{{ onQuickFormEvent()
528 function onQuickFormEvent($event, $arg, &$caller)
530 if ('updateValue' == $event) {
531 $value = $this->_findValue($caller->_constantValues
);
532 if (null === $value) {
533 $value = $this->_findValue($caller->_submitValues
);
534 // Fix for bug #4465 & #5269
535 // XXX: should we push this to element::onQuickFormEvent()?
536 if (null === $value && (!$caller->isSubmitted() ||
!$this->getMultiple())) {
537 $value = $this->_findValue($caller->_defaultValues
);
540 if (null !== $value) {
541 $this->setValue($value);
545 return parent
::onQuickFormEvent($event, $arg, $caller);
548 function setHiddenLabel($hiddenLabel){
549 $this->_hiddenLabel
= $hiddenLabel;
552 * Automatically generates and assigns an 'id' attribute for the element.
554 * Currently used to ensure that labels work on radio buttons and
555 * checkboxes. Per idea of Alexander Radivanovich.
556 * Overriden in moodleforms to remove qf_ prefix.
561 function _generateId()
565 if (!$this->getAttribute('id')) {
566 $this->updateAttributes(array('id' => 'id_'. substr(md5(microtime() . $idx++
), 0, 6)));
568 } // end func _generateId
570 * set html for help button
573 * @param array $help array of arguments to make a help button
574 * @param string $function function name to call to get html
576 function setHelpButton($helpbuttonargs, $function='helpbutton'){
577 debugging('component setHelpButton() is not used any more, please use $mform->setHelpButton() instead');
580 * get html for help button
583 * @return string html for help button
585 function getHelpButton(){
586 return $this->_helpbutton
;
590 * Slightly different container template when frozen. Don't want to use a label tag
591 * with a for attribute in that case for the element label but instead use a div.
592 * Templates are defined in renderer constructor.
596 function getElementTemplateType(){
597 if ($this->_flagFrozen
){