MDL-9137 Fixing errors in the overview report
[moodle-pu.git] / lib / form / selectgroups.php
blobc226f5da6e7b2f847e3865ea5acab5499c28fda7
1 <?php
2 /* vim: set expandtab tabstop=4 shiftwidth=4: */
3 // +----------------------------------------------------------------------+
4 // | PHP version 4.0 |
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 // $Id$
22 require_once('HTML/QuickForm/element.php');
24 /**
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>
29 * @version 1.0
30 * @since PHP4.04pl1
31 * @access public
33 class MoodleQuickForm_selectgroups extends HTML_QuickForm_element {
35 // {{{ properties
37 /**
38 * Contains the select optgroups
40 * @var array
41 * @since 1.0
42 * @access private
44 var $_optGroups = array();
46 /**
47 * Default values of the SELECT
49 * @var string
50 * @since 1.0
51 * @access private
53 var $_values = null;
55 /**
56 * html for help button, if empty then no help
58 * @var string
60 var $_helpbutton='';
61 var $_hiddenLabel=false;
63 /**
64 * Class constructor
66 * @param string Select name attribute
67 * @param mixed Label(s) for the select
68 * @param mixed Data to be used to populate options
69 * @param mixed An array whose keys are labels for optgroups and whose values are arrays similar to those passed
70 * to the select element with keys that are values for options and values are strings for display.
71 * @param mixed Either a typical HTML attribute string or an associative array
72 * @since 1.0
73 * @access public
74 * @return void
76 function MoodleQuickForm_selectgroups($elementName=null, $elementLabel=null, $optgrps=null, $attributes=null)
78 HTML_QuickForm_element::HTML_QuickForm_element($elementName, $elementLabel, $attributes);
79 $this->_persistantFreeze = true;
80 $this->_type = 'selectgroups';
81 if (isset($optgrps)) {
82 $this->loadArrayOptGroups($optgrps);
84 } //end constructor
86 // }}}
87 // {{{ apiVersion()
90 /**
91 * Sets the default values of the select box
93 * @param mixed $values Array or comma delimited string of selected values
94 * @since 1.0
95 * @access public
96 * @return void
98 function setSelected($values)
100 if (is_string($values) && $this->getMultiple()) {
101 $values = split("[ ]?,[ ]?", $values);
103 if (is_array($values)) {
104 $this->_values = array_values($values);
105 } else {
106 $this->_values = array($values);
108 } //end func setSelected
110 // }}}
111 // {{{ getSelected()
114 * Returns an array of the selected values
116 * @since 1.0
117 * @access public
118 * @return array of selected values
120 function getSelected()
122 return $this->_values;
123 } // end func getSelected
125 // }}}
126 // {{{ setName()
129 * Sets the input field name
131 * @param string $name Input field name attribute
132 * @since 1.0
133 * @access public
134 * @return void
136 function setName($name)
138 $this->updateAttributes(array('name' => $name));
139 } //end func setName
141 // }}}
142 // {{{ getName()
145 * Returns the element name
147 * @since 1.0
148 * @access public
149 * @return string
151 function getName()
153 return $this->getAttribute('name');
154 } //end func getName
156 // }}}
157 // {{{ getPrivateName()
160 * Returns the element name (possibly with brackets appended)
162 * @since 1.0
163 * @access public
164 * @return string
166 function getPrivateName()
168 if ($this->getAttribute('multiple')) {
169 return $this->getName() . '[]';
170 } else {
171 return $this->getName();
173 } //end func getPrivateName
175 // }}}
176 // {{{ setValue()
179 * Sets the value of the form element
181 * @param mixed $values Array or comma delimited string of selected values
182 * @since 1.0
183 * @access public
184 * @return void
186 function setValue($value)
188 $this->setSelected($value);
189 } // end func setValue
191 // }}}
192 // {{{ getValue()
195 * Returns an array of the selected values
197 * @since 1.0
198 * @access public
199 * @return array of selected values
201 function getValue()
203 return $this->_values;
204 } // end func getValue
206 // }}}
207 // {{{ setSize()
210 * Sets the select field size, only applies to 'multiple' selects
212 * @param int $size Size of select field
213 * @since 1.0
214 * @access public
215 * @return void
217 function setSize($size)
219 $this->updateAttributes(array('size' => $size));
220 } //end func setSize
222 // }}}
223 // {{{ getSize()
226 * Returns the select field size
228 * @since 1.0
229 * @access public
230 * @return int
232 function getSize()
234 return $this->getAttribute('size');
235 } //end func getSize
237 // }}}
238 // {{{ setMultiple()
241 * Sets the select mutiple attribute
243 * @param bool $multiple Whether the select supports multi-selections
244 * @since 1.2
245 * @access public
246 * @return void
248 function setMultiple($multiple)
250 if ($multiple) {
251 $this->updateAttributes(array('multiple' => 'multiple'));
252 } else {
253 $this->removeAttribute('multiple');
255 } //end func setMultiple
257 // }}}
258 // {{{ getMultiple()
261 * Returns the select mutiple attribute
263 * @since 1.2
264 * @access public
265 * @return bool true if multiple select, false otherwise
267 function getMultiple()
269 return (bool)$this->getAttribute('multiple');
270 } //end func getMultiple
273 * Loads the options from an associative array
275 * @param array $arr Associative array of options
276 * @param mixed $values (optional) Array or comma delimited string of selected values
277 * @since 1.0
278 * @access public
279 * @return PEAR_Error on error or true
280 * @throws PEAR_Error
282 function loadArrayOptGroups($arr, $values=null)
284 if (!is_array($arr)) {
285 return PEAR::raiseError('Argument 1 of HTML_Select::loadArrayOptGroups is not a valid array');
287 if (isset($values)) {
288 $this->setSelected($values);
290 foreach ($arr as $key => $val) {
291 // Warning: new API since release 2.3
292 $this->addOptGroup($key, $val);
294 return true;
297 * Adds a new OPTION to the SELECT
299 * @param string $text Display text for the OPTION
300 * @param string $value Value for the OPTION
301 * @param mixed $attributes Either a typical HTML attribute string
302 * or an associative array
303 * @since 1.0
304 * @access public
305 * @return void
307 function addOptGroup($text, $value, $attributes=null)
309 if (null === $attributes) {
310 $attributes = array('label' => $text);
311 } else {
312 $attributes = $this->_parseAttributes($attributes);
313 $this->_updateAttrArray($attributes, array('label' => $text));
315 $index = count($this->_optGroups);
316 $this->_optGroups[$index] = array('attr' => $attributes);
317 $this->loadArrayOptions($index, $value);
321 * Loads the options from an associative array
323 * @param array $arr Associative array of options
324 * @param mixed $values (optional) Array or comma delimited string of selected values
325 * @since 1.0
326 * @access public
327 * @return PEAR_Error on error or true
328 * @throws PEAR_Error
330 function loadArrayOptions($optgroup, $arr, $values=null)
332 if (!is_array($arr)) {
333 return PEAR::raiseError('Argument 1 of HTML_Select::loadArray is not a valid array');
335 if (isset($values)) {
336 $this->setSelected($values);
338 foreach ($arr as $key => $val) {
339 // Warning: new API since release 2.3
340 $this->addOption($optgroup, $val, $key);
342 return true;
346 * Adds a new OPTION to an optgroup
348 * @param string $text Display text for the OPTION
349 * @param string $value Value for the OPTION
350 * @param mixed $attributes Either a typical HTML attribute string
351 * or an associative array
352 * @since 1.0
353 * @access public
354 * @return void
356 function addOption($optgroup, $text, $value, $attributes=null)
358 if (null === $attributes) {
359 $attributes = array('value' => $value);
360 } else {
361 $attributes = $this->_parseAttributes($attributes);
362 if (isset($attributes['selected'])) {
363 // the 'selected' attribute will be set in toHtml()
364 $this->_removeAttr('selected', $attributes);
365 if (is_null($this->_values)) {
366 $this->_values = array($value);
367 } elseif (!in_array($value, $this->_values)) {
368 $this->_values[] = $value;
371 $this->_updateAttrArray($attributes, array('value' => $value));
373 $this->_optGroups[$optgroup]['options'][] = array('text' => $text, 'attr' => $attributes);
377 * Returns the SELECT in HTML
379 * @since 1.0
380 * @access public
381 * @return string
383 function toHtml()
385 if ($this->_flagFrozen) {
386 return $this->getFrozenHtml();
387 } else {
388 $tabs = $this->_getTabs();
389 $strHtml = '';
391 if ($this->getComment() != '') {
392 $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
395 if (!$this->getMultiple()) {
396 $attrString = $this->_getAttrString($this->_attributes);
397 } else {
398 $myName = $this->getName();
399 $this->setName($myName . '[]');
400 $attrString = $this->_getAttrString($this->_attributes);
401 $this->setName($myName);
403 $strHtml .= $tabs;
404 if ($this->_hiddenLabel){
405 $this->_generateId();
406 $strHtml .= '<label class="accesshide" for="'.$this->getAttribute('id').'" >'.
407 $this->getLabel().'</label>';
409 $strHtml .= '<select' . $attrString . ">\n";
410 foreach ($this->_optGroups as $optGroup) {
411 $strHtml .= $tabs . "\t<optgroup" . ($this->_getAttrString($optGroup['attr'])) . '>';
412 foreach ($optGroup['options'] as $option){
413 if (is_array($this->_values) && in_array((string)$option['attr']['value'], $this->_values)) {
414 $this->_updateAttrArray($option['attr'], array('selected' => 'selected'));
416 $strHtml .= $tabs . "\t\t<option" . $this->_getAttrString($option['attr']) . '>' .
417 $option['text'] . "</option>\n";
419 $strHtml .= $tabs . "\t</optgroup>\n";
421 return $strHtml . $tabs . '</select>';
423 } //end func toHtml
425 // }}}
426 // {{{ getFrozenHtml()
429 * Returns the value of field without HTML tags
431 * @since 1.0
432 * @access public
433 * @return string
435 function getFrozenHtml()
437 $value = array();
438 if (is_array($this->_values)) {
439 foreach ($this->_values as $key => $val) {
440 foreach ($this->_optGroups as $optGroup) {
441 for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++) {
442 if ((string)$val == (string)$optGroup['options'][$i]['attr']['value']) {
443 $value[$key] = $optGroup['options'][$i]['text'];
444 break;
450 $html = empty($value)? '&nbsp;': join('<br />', $value);
451 if ($this->_persistantFreeze) {
452 $name = $this->getPrivateName();
453 // Only use id attribute if doing single hidden input
454 if (1 == count($value)) {
455 $id = $this->getAttribute('id');
456 $idAttr = isset($id)? array('id' => $id): array();
457 } else {
458 $idAttr = array();
460 foreach ($value as $key => $item) {
461 $html .= '<input' . $this->_getAttrString(array(
462 'type' => 'hidden',
463 'name' => $name,
464 'value' => $this->_values[$key]
465 ) + $idAttr) . ' />';
468 return $html;
469 } //end func getFrozenHtml
471 // }}}
472 // {{{ exportValue()
475 * We check the options and return only the values that _could_ have been
476 * selected. We also return a scalar value if select is not "multiple"
478 function exportValue(&$submitValues, $assoc = false)
480 $value = $this->_findValue($submitValues);
481 if (is_null($value)) {
482 $value = $this->getValue();
483 } elseif(!is_array($value)) {
484 $value = array($value);
486 if (is_array($value) && !empty($this->_optGroups)) {
487 $cleanValue = null;
488 foreach ($value as $v) {
489 foreach ($this->_optGroups as $optGroup){
490 for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++) {
491 if ($v == $optGroup['options'][$i]['attr']['value']) {
492 $cleanValue[] = $v;
493 break;
498 } else {
499 $cleanValue = $value;
501 if (is_array($cleanValue) && !$this->getMultiple()) {
502 return $this->_prepareValue($cleanValue[0], $assoc);
503 } else {
504 return $this->_prepareValue($cleanValue, $assoc);
508 // }}}
509 // {{{ onQuickFormEvent()
511 function onQuickFormEvent($event, $arg, &$caller)
513 if ('updateValue' == $event) {
514 $value = $this->_findValue($caller->_constantValues);
515 if (null === $value) {
516 $value = $this->_findValue($caller->_submitValues);
517 // Fix for bug #4465 & #5269
518 // XXX: should we push this to element::onQuickFormEvent()?
519 if (null === $value && (!$caller->isSubmitted() || !$this->getMultiple())) {
520 $value = $this->_findValue($caller->_defaultValues);
523 if (null !== $value) {
524 $this->setValue($value);
526 return true;
527 } else {
528 return parent::onQuickFormEvent($event, $arg, $caller);
531 function setHiddenLabel($hiddenLabel){
532 $this->_hiddenLabel = $hiddenLabel;
535 * Automatically generates and assigns an 'id' attribute for the element.
537 * Currently used to ensure that labels work on radio buttons and
538 * checkboxes. Per idea of Alexander Radivanovich.
539 * Overriden in moodleforms to remove qf_ prefix.
541 * @access private
542 * @return void
544 function _generateId()
546 static $idx = 1;
548 if (!$this->getAttribute('id')) {
549 $this->updateAttributes(array('id' => 'id_'. substr(md5(microtime() . $idx++), 0, 6)));
551 } // end func _generateId
553 * set html for help button
555 * @access public
556 * @param array $help array of arguments to make a help button
557 * @param string $function function name to call to get html
559 function setHelpButton($helpbuttonargs, $function='helpbutton'){
560 if (!is_array($helpbuttonargs)){
561 $helpbuttonargs=array($helpbuttonargs);
562 }else{
563 $helpbuttonargs=$helpbuttonargs;
565 //we do this to to return html instead of printing it
566 //without having to specify it in every call to make a button.
567 if ('helpbutton' == $function){
568 $defaultargs=array('', '', 'moodle', true, false, '', true);
569 $helpbuttonargs=$helpbuttonargs + $defaultargs ;
571 $this->_helpbutton=call_user_func_array($function, $helpbuttonargs);
574 * get html for help button
576 * @access public
577 * @return string html for help button
579 function getHelpButton(){
580 return $this->_helpbutton;
584 * Slightly different container template when frozen. Don't want to use a label tag
585 * with a for attribute in that case for the element label but instead use a div.
586 * Templates are defined in renderer constructor.
588 * @return string
590 function getElementTemplateType(){
591 if ($this->_flagFrozen){
592 return 'static';
593 } else {
594 return 'default';