timeline: if a section is set to hidden and the user is not capable of editing a...
[moodle-blog-course-format.git] / lib / form / selectgroups.php
blob733b4154020df4d7dbde327b9a62db181530fe34
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 /** add choose option */
38 var $showchoose = false;
40 /**
41 * Contains the select optgroups
43 * @var array
44 * @since 1.0
45 * @access private
47 var $_optGroups = array();
49 /**
50 * Default values of the SELECT
52 * @var string
53 * @since 1.0
54 * @access private
56 var $_values = null;
58 /**
59 * html for help button, if empty then no help
61 * @var string
63 var $_helpbutton='';
64 var $_hiddenLabel=false;
66 /**
67 * Class constructor
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
76 * @since 1.0
77 * @access public
78 * @return void
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);
89 } //end constructor
91 // }}}
92 // {{{ apiVersion()
95 /**
96 * Sets the default values of the select box
98 * @param mixed $values Array or comma delimited string of selected values
99 * @since 1.0
100 * @access public
101 * @return void
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);
110 } else {
111 $this->_values = array($values);
113 } //end func setSelected
115 // }}}
116 // {{{ getSelected()
119 * Returns an array of the selected values
121 * @since 1.0
122 * @access public
123 * @return array of selected values
125 function getSelected()
127 return $this->_values;
128 } // end func getSelected
130 // }}}
131 // {{{ setName()
134 * Sets the input field name
136 * @param string $name Input field name attribute
137 * @since 1.0
138 * @access public
139 * @return void
141 function setName($name)
143 $this->updateAttributes(array('name' => $name));
144 } //end func setName
146 // }}}
147 // {{{ getName()
150 * Returns the element name
152 * @since 1.0
153 * @access public
154 * @return string
156 function getName()
158 return $this->getAttribute('name');
159 } //end func getName
161 // }}}
162 // {{{ getPrivateName()
165 * Returns the element name (possibly with brackets appended)
167 * @since 1.0
168 * @access public
169 * @return string
171 function getPrivateName()
173 if ($this->getAttribute('multiple')) {
174 return $this->getName() . '[]';
175 } else {
176 return $this->getName();
178 } //end func getPrivateName
180 // }}}
181 // {{{ setValue()
184 * Sets the value of the form element
186 * @param mixed $values Array or comma delimited string of selected values
187 * @since 1.0
188 * @access public
189 * @return void
191 function setValue($value)
193 $this->setSelected($value);
194 } // end func setValue
196 // }}}
197 // {{{ getValue()
200 * Returns an array of the selected values
202 * @since 1.0
203 * @access public
204 * @return array of selected values
206 function getValue()
208 return $this->_values;
209 } // end func getValue
211 // }}}
212 // {{{ setSize()
215 * Sets the select field size, only applies to 'multiple' selects
217 * @param int $size Size of select field
218 * @since 1.0
219 * @access public
220 * @return void
222 function setSize($size)
224 $this->updateAttributes(array('size' => $size));
225 } //end func setSize
227 // }}}
228 // {{{ getSize()
231 * Returns the select field size
233 * @since 1.0
234 * @access public
235 * @return int
237 function getSize()
239 return $this->getAttribute('size');
240 } //end func getSize
242 // }}}
243 // {{{ setMultiple()
246 * Sets the select mutiple attribute
248 * @param bool $multiple Whether the select supports multi-selections
249 * @since 1.2
250 * @access public
251 * @return void
253 function setMultiple($multiple)
255 if ($multiple) {
256 $this->updateAttributes(array('multiple' => 'multiple'));
257 } else {
258 $this->removeAttribute('multiple');
260 } //end func setMultiple
262 // }}}
263 // {{{ getMultiple()
266 * Returns the select mutiple attribute
268 * @since 1.2
269 * @access public
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
282 * @since 1.0
283 * @access public
284 * @return PEAR_Error on error or true
285 * @throws PEAR_Error
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);
299 return true;
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
308 * @since 1.0
309 * @access public
310 * @return void
312 function addOptGroup($text, $value, $attributes=null)
314 if (null === $attributes) {
315 $attributes = array('label' => $text);
316 } else {
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
330 * @since 1.0
331 * @access public
332 * @return PEAR_Error on error or true
333 * @throws PEAR_Error
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);
347 return true;
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
357 * @since 1.0
358 * @access public
359 * @return void
361 function addOption($optgroup, $text, $value, $attributes=null)
363 if (null === $attributes) {
364 $attributes = array('value' => $value);
365 } else {
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
384 * @since 1.0
385 * @access public
386 * @return string
388 function toHtml()
390 if ($this->_flagFrozen) {
391 return $this->getFrozenHtml();
392 } else {
393 $tabs = $this->_getTabs();
394 $strHtml = '';
396 if ($this->getComment() != '') {
397 $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
400 if (!$this->getMultiple()) {
401 $attrString = $this->_getAttrString($this->_attributes);
402 } else {
403 $myName = $this->getName();
404 $this->setName($myName . '[]');
405 $attrString = $this->_getAttrString($this->_attributes);
406 $this->setName($myName);
408 $strHtml .= $tabs;
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'])) {
420 //xhtml strict
421 continue;
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>';
435 } //end func toHtml
437 // }}}
438 // {{{ getFrozenHtml()
441 * Returns the value of field without HTML tags
443 * @since 1.0
444 * @access public
445 * @return string
447 function getFrozenHtml()
449 $value = array();
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'];
456 break;
462 $html = empty($value)? '&nbsp;': 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();
469 } else {
470 $idAttr = array();
472 foreach ($value as $key => $item) {
473 $html .= '<input' . $this->_getAttrString(array(
474 'type' => 'hidden',
475 'name' => $name,
476 'value' => $this->_values[$key]
477 ) + $idAttr) . ' />';
480 return $html;
481 } //end func getFrozenHtml
483 // }}}
484 // {{{ exportValue()
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)) {
499 $cleanValue = null;
500 foreach ($value as $v) {
501 foreach ($this->_optGroups as $optGroup){
502 if (empty($optGroup['options'])) {
503 continue;
505 for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++) {
506 if ($v == $optGroup['options'][$i]['attr']['value']) {
507 $cleanValue[] = $v;
508 break;
513 } else {
514 $cleanValue = $value;
516 if (is_array($cleanValue) && !$this->getMultiple()) {
517 return $this->_prepareValue($cleanValue[0], $assoc);
518 } else {
519 return $this->_prepareValue($cleanValue, $assoc);
523 // }}}
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);
541 return true;
542 } else {
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.
556 * @access private
557 * @return void
559 function _generateId()
561 static $idx = 1;
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
570 * @access public
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);
577 }else{
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
591 * @access public
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.
603 * @return string
605 function getElementTemplateType(){
606 if ($this->_flagFrozen){
607 return 'static';
608 } else {
609 return 'default';