[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/lib/form/ -> selectgroups.php (source)

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  
  18  /**
  19   * select type form element
  20   *
  21   * Class to dynamically create an HTML SELECT with all options grouped in optgroups
  22   *
  23   * @package   core_form
  24   * @copyright 2007 Jamie Pratt <me@jamiep.org>
  25   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  require_once('HTML/QuickForm/element.php');
  29  
  30  /**
  31   * select type form element
  32   *
  33   * Class to dynamically create an HTML SELECT with all options grouped in optgroups
  34   *
  35   * @package   core_form
  36   * @category  form
  37   * @copyright 2007 Jamie Pratt <me@jamiep.org>
  38   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  39   */
  40  class MoodleQuickForm_selectgroups extends HTML_QuickForm_element {
  41  
  42      /** @var bool add choose option */
  43      var $showchoose = false;
  44  
  45      /** @var array Contains the select optgroups */
  46      var $_optGroups = array();
  47  
  48      /** @var string Default values of the SELECT */
  49      var $_values = null;
  50  
  51      /** @var string html for help button, if empty then no help */
  52      var $_helpbutton='';
  53  
  54      /** @var bool if true label will be hidden */
  55      var $_hiddenLabel=false;
  56  
  57      /**
  58       * Class constructor
  59       *
  60       * @param string $elementName Select name attribute
  61       * @param mixed $elementLabel Label(s) for the select
  62       * @param array $optgrps Data to be used to populate options
  63       * @param mixed $attributes Either a typical HTML attribute string or an associative array
  64       * @param bool $showchoose add standard moodle "Choose..." option as first item
  65       */
  66      public function __construct($elementName=null, $elementLabel=null, $optgrps=null, $attributes=null, $showchoose=false)
  67      {
  68          $this->showchoose = $showchoose;
  69          parent::__construct($elementName, $elementLabel, $attributes);
  70          $this->_persistantFreeze = true;
  71          $this->_type = 'selectgroups';
  72          if (isset($optgrps)) {
  73              $this->loadArrayOptGroups($optgrps);
  74          }
  75      }
  76  
  77      /**
  78       * Old syntax of class constructor. Deprecated in PHP7.
  79       *
  80       * @deprecated since Moodle 3.1
  81       */
  82      public function MoodleQuickForm_selectgroups($elementName=null, $elementLabel=null, $optgrps=null, $attributes=null, $showchoose=false) {
  83          debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
  84          self::__construct($elementName, $elementLabel, $optgrps, $attributes, $showchoose);
  85      }
  86  
  87      /**
  88       * Sets the default values of the select box
  89       *
  90       * @param mixed $values Array or comma delimited string of selected values
  91       */
  92      function setSelected($values)
  93      {
  94          if (is_string($values) && $this->getMultiple()) {
  95              $values = preg_split("/[ ]?,[ ]?/", $values);
  96          }
  97          if (is_array($values)) {
  98              $this->_values = array_values($values);
  99          } else {
 100              $this->_values = array($values);
 101          }
 102      }
 103  
 104      /**
 105       * Returns an array of the selected values
 106       *
 107       * @return array of selected values
 108       */
 109      function getSelected()
 110      {
 111          return $this->_values;
 112      }
 113  
 114      /**
 115       * Sets the input field name
 116       *
 117       * @param string $name Input field name attribute
 118       */
 119      function setName($name)
 120      {
 121          $this->updateAttributes(array('name' => $name));
 122      }
 123  
 124      /**
 125       * Returns the element name
 126       *
 127       * @return string
 128       */
 129      function getName()
 130      {
 131          return $this->getAttribute('name');
 132      }
 133  
 134      /**
 135       * Returns the element name (possibly with brackets appended)
 136       *
 137       * @return string
 138       */
 139      function getPrivateName()
 140      {
 141          if ($this->getAttribute('multiple')) {
 142              return $this->getName() . '[]';
 143          } else {
 144              return $this->getName();
 145          }
 146      }
 147  
 148      /**
 149       * Sets the value of the form element
 150       *
 151       * @param mixed $value Array or comma delimited string of selected values
 152       */
 153      function setValue($value)
 154      {
 155          $this->setSelected($value);
 156      }
 157  
 158      /**
 159       * Returns an array of the selected values
 160       *
 161       * @return array of selected values
 162       */
 163      function getValue()
 164      {
 165          return $this->_values;
 166      }
 167  
 168      /**
 169       * Sets the select field size, only applies to 'multiple' selects
 170       *
 171       * @param int $size Size of select  field
 172       */
 173      function setSize($size)
 174      {
 175          $this->updateAttributes(array('size' => $size));
 176      }
 177  
 178      /**
 179       * Returns the select field size
 180       *
 181       * @return int
 182       */
 183      function getSize()
 184      {
 185          return $this->getAttribute('size');
 186      }
 187  
 188      /**
 189       * Sets the select mutiple attribute
 190       *
 191       * @param bool $multiple Whether the select supports multi-selections
 192       */
 193      function setMultiple($multiple)
 194      {
 195          if ($multiple) {
 196              $this->updateAttributes(array('multiple' => 'multiple'));
 197          } else {
 198              $this->removeAttribute('multiple');
 199          }
 200      }
 201  
 202      /**
 203       * Returns the select mutiple attribute
 204       *
 205       * @return bool true if multiple select, false otherwise
 206       */
 207      function getMultiple()
 208      {
 209          return (bool)$this->getAttribute('multiple');
 210      }
 211  
 212      /**
 213       * Loads the options from an associative array
 214       *
 215       * @param array $arr Associative array of options
 216       * @param mixed $values (optional) Array or comma delimited string of selected values
 217       * @return PEAR_Error|bool on error or true
 218       * @throws PEAR_Error
 219       */
 220      function loadArrayOptGroups($arr, $values=null)
 221      {
 222          if (!is_array($arr)) {
 223              return self::raiseError('Argument 1 of HTML_Select::loadArrayOptGroups is not a valid array');
 224          }
 225          if (isset($values)) {
 226              $this->setSelected($values);
 227          }
 228          foreach ($arr as $key => $val) {
 229              // Warning: new API since release 2.3
 230              $this->addOptGroup($key, $val);
 231          }
 232          return true;
 233      }
 234  
 235      /**
 236       * Adds a new OPTION to the SELECT
 237       *
 238       * @param string $text Display text for the OPTION
 239       * @param string $value Value for the OPTION
 240       * @param mixed $attributes Either a typical HTML attribute string
 241       *              or an associative array
 242       */
 243      function addOptGroup($text, $value, $attributes=null)
 244      {
 245          if (null === $attributes) {
 246              $attributes = array('label' => $text);
 247          } else {
 248              $attributes = $this->_parseAttributes($attributes);
 249              $this->_updateAttrArray($attributes, array('label' => $text));
 250          }
 251          $index = count($this->_optGroups);
 252          $this->_optGroups[$index] = array('attr' => $attributes);
 253          $this->loadArrayOptions($index, $value);
 254      }
 255  
 256      /**
 257       * Loads the options from an associative array
 258       *
 259       * @param string $optgroup name of the options group
 260       * @param array $arr Associative array of options
 261       * @param mixed $values (optional) Array or comma delimited string of selected values
 262       * @return PEAR_Error|bool on error or true
 263       * @throws PEAR_Error
 264       */
 265      function loadArrayOptions($optgroup, $arr, $values=null)
 266      {
 267          if (!is_array($arr)) {
 268              return self::raiseError('Argument 1 of HTML_Select::loadArray is not a valid array');
 269          }
 270          if (isset($values)) {
 271              $this->setSelected($values);
 272          }
 273          foreach ($arr as $key => $val) {
 274              // Warning: new API since release 2.3
 275              $this->addOption($optgroup, $val, $key);
 276          }
 277          return true;
 278      }
 279  
 280      /**
 281       * Adds a new OPTION to an optgroup
 282       *
 283       * @param string $optgroup name of the option group
 284       * @param string $text Display text for the OPTION
 285       * @param string $value Value for the OPTION
 286       * @param mixed $attributes Either a typical HTML attribute string
 287       *              or an associative array
 288       */
 289      function addOption($optgroup, $text, $value, $attributes=null)
 290      {
 291          if (null === $attributes) {
 292              $attributes = array('value' => $value);
 293          } else {
 294              $attributes = $this->_parseAttributes($attributes);
 295              if (isset($attributes['selected'])) {
 296                  // the 'selected' attribute will be set in toHtml()
 297                  $this->_removeAttr('selected', $attributes);
 298                  if (is_null($this->_values)) {
 299                      $this->_values = array($value);
 300                  } elseif (!in_array($value, $this->_values)) {
 301                      $this->_values[] = $value;
 302                  }
 303              }
 304              $this->_updateAttrArray($attributes, array('value' => $value));
 305          }
 306          $this->_optGroups[$optgroup]['options'][] = array('text' => $text, 'attr' => $attributes);
 307      }
 308  
 309      /**
 310       * Returns the SELECT in HTML
 311       *
 312       * @return string
 313       */
 314      function toHtml()
 315      {
 316          if ($this->_flagFrozen) {
 317              return $this->getFrozenHtml();
 318          } else {
 319              $tabs    = $this->_getTabs();
 320              $strHtml = '';
 321  
 322              if ($this->getComment() != '') {
 323                  $strHtml .= $tabs . '<!-- ' . $this->getComment() . " //-->\n";
 324              }
 325  
 326              if (!$this->getMultiple()) {
 327                  $attrString = $this->_getAttrString($this->_attributes);
 328              } else {
 329                  $myName = $this->getName();
 330                  $this->setName($myName . '[]');
 331                  $attrString = $this->_getAttrString($this->_attributes);
 332                  $this->setName($myName);
 333              }
 334              $strHtml .= $tabs;
 335              if ($this->_hiddenLabel){
 336                  $this->_generateId();
 337                  $strHtml .= '<label class="accesshide" for="'.$this->getAttribute('id').'" >'.
 338                              $this->getLabel().'</label>';
 339              }
 340              $strHtml .=  '<select' . $attrString . ">\n";
 341              if ($this->showchoose) {
 342                  $strHtml .= $tabs . "\t\t<option value=\"\">" . get_string('choose') . "...</option>\n";
 343              }
 344              foreach ($this->_optGroups as $optGroup) {
 345                  if (empty($optGroup['options'])) {
 346                      //xhtml strict
 347                      continue;
 348                  }
 349                  $strHtml .= $tabs . "\t<optgroup" . ($this->_getAttrString($optGroup['attr'])) . '>';
 350                  foreach ($optGroup['options'] as $option){
 351                      if (is_array($this->_values) && in_array((string)$option['attr']['value'], $this->_values)) {
 352                          $this->_updateAttrArray($option['attr'], array('selected' => 'selected'));
 353                      }
 354                      $strHtml .= $tabs . "\t\t<option" . $this->_getAttrString($option['attr']) . '>' .
 355                                  $option['text'] . "</option>\n";
 356                  }
 357                  $strHtml .= $tabs . "\t</optgroup>\n";
 358              }
 359              return $strHtml . $tabs . '</select>';
 360          }
 361      }
 362  
 363      /**
 364       * Returns the value of field without HTML tags
 365       *
 366       * @return string
 367       */
 368      function getFrozenHtml()
 369      {
 370          $value = array();
 371          if (is_array($this->_values)) {
 372              foreach ($this->_values as $key => $val) {
 373                  foreach ($this->_optGroups as $optGroup) {
 374                      for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++) {
 375                          if ((string)$val == (string)$optGroup['options'][$i]['attr']['value']) {
 376                              $value[$key] = $optGroup['options'][$i]['text'];
 377                              break;
 378                          }
 379                      }
 380                  }
 381              }
 382          }
 383          $html = empty($value)? '&nbsp;': join('<br />', $value);
 384          if ($this->_persistantFreeze) {
 385              $name = $this->getPrivateName();
 386              // Only use id attribute if doing single hidden input
 387              if (1 == count($value)) {
 388                  $id     = $this->getAttribute('id');
 389                  $idAttr = isset($id)? array('id' => $id): array();
 390              } else {
 391                  $idAttr = array();
 392              }
 393              foreach ($value as $key => $item) {
 394                  $html .= '<input' . $this->_getAttrString(array(
 395                               'type'  => 'hidden',
 396                               'name'  => $name,
 397                               'value' => $this->_values[$key]
 398                           ) + $idAttr) . ' />';
 399              }
 400          }
 401          return $html;
 402      }
 403  
 404     /**
 405      * We check the options and return only the values that _could_ have been
 406      * selected. We also return a scalar value if select is not "multiple"
 407      *
 408      * @param array $submitValues submitted values
 409      * @param bool $assoc if true the retured value is associated array
 410      * @return mixed
 411      */
 412      function exportValue(&$submitValues, $assoc = false)
 413      {
 414          if (empty($this->_optGroups)) {
 415              return $this->_prepareValue(null, $assoc);
 416          }
 417  
 418          $value = $this->_findValue($submitValues);
 419          if (is_null($value)) {
 420              $value = $this->getValue();
 421          }
 422          $value = (array)$value;
 423  
 424          $cleaned = array();
 425          foreach ($value as $v) {
 426              foreach ($this->_optGroups as $optGroup){
 427                  if (empty($optGroup['options'])) {
 428                      continue;
 429                  }
 430                  foreach ($optGroup['options'] as $option) {
 431                      if ((string)$option['attr']['value'] === (string)$v) {
 432                          $cleaned[] = (string)$option['attr']['value'];
 433                          break;
 434                      }
 435                  }
 436              }
 437          }
 438  
 439          if (empty($cleaned)) {
 440              return $this->_prepareValue(null, $assoc);
 441          }
 442          if ($this->getMultiple()) {
 443              return $this->_prepareValue($cleaned, $assoc);
 444          } else {
 445              return $this->_prepareValue($cleaned[0], $assoc);
 446          }
 447      }
 448  
 449      /**
 450       * Called by HTML_QuickForm whenever form event is made on this element
 451       *
 452       * @param string $event Name of event
 453       * @param mixed $arg event arguments
 454       * @param object $caller calling object
 455       * @return bool
 456       */
 457      function onQuickFormEvent($event, $arg, &$caller)
 458      {
 459          if ('updateValue' == $event) {
 460              $value = $this->_findValue($caller->_constantValues);
 461              if (null === $value) {
 462                  $value = $this->_findValue($caller->_submitValues);
 463                  // Fix for bug #4465 & #5269
 464                  // XXX: should we push this to element::onQuickFormEvent()?
 465                  if (null === $value && (!$caller->isSubmitted() || !$this->getMultiple())) {
 466                      $value = $this->_findValue($caller->_defaultValues);
 467                  }
 468              }
 469              if (null !== $value) {
 470                  $this->setValue($value);
 471              }
 472              return true;
 473          } else {
 474              return parent::onQuickFormEvent($event, $arg, $caller);
 475          }
 476      }
 477  
 478      /**
 479       * Sets label to be hidden
 480       *
 481       * @param bool $hiddenLabel sets if label should be hidden
 482       */
 483      function setHiddenLabel($hiddenLabel){
 484          $this->_hiddenLabel = $hiddenLabel;
 485      }
 486  
 487      /**
 488       * get html for help button
 489       *
 490       * @return string html for help button
 491       */
 492      function getHelpButton(){
 493          return $this->_helpbutton;
 494      }
 495  
 496      /**
 497       * Slightly different container template when frozen. Don't want to use a label tag
 498       * with a for attribute in that case for the element label but instead use a div.
 499       * Templates are defined in renderer constructor.
 500       *
 501       * @return string
 502       */
 503      function getElementTemplateType(){
 504          if ($this->_flagFrozen){
 505              return 'static';
 506          } else {
 507              return 'default';
 508          }
 509      }
 510  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1