1<?php 2 3namespace dokuwiki\Form; 4 5 6class OptGroup extends Element { 7 protected $options = array(); 8 protected $value; 9 10 /** 11 * @param string $label The label text for this element (will be autoescaped) 12 * @param array $options The available options 13 */ 14 public function __construct($label, $options) { 15 parent::__construct('optGroup', array('label' => $label)); 16 $this->options($options); 17 } 18 19 /** 20 * Store the given value so it can be used during rendering 21 * 22 * This is intended to be only called from within @see DropdownElement::val() 23 * 24 * @param string $value 25 * @return bool true if an option with the given value exists, false otherwise 26 */ 27 public function storeValue($value) { 28 $this->value = $value; 29 return isset($this->options[$value]); 30 } 31 32 /** 33 * Get or set the options of the optgroup 34 * 35 * Options can be given as associative array (value => label) or as an 36 * indexd array (label = value) or as an array of arrays. In the latter 37 * case an element has to look as follows: 38 * option-value => array ( 39 * 'label' => option-label, 40 * 'attrs' => array ( 41 * attr-key => attr-value, ... 42 * ) 43 * ) 44 * 45 * @param null|array $options 46 * @return $this|array 47 */ 48 public function options($options = null) { 49 if($options === null) return $this->options; 50 if(!is_array($options)) throw new \InvalidArgumentException('Options have to be an array'); 51 $this->options = array(); 52 foreach($options as $key => $val) { 53 if (is_array($val)) { 54 if (!key_exists('label', $val)) throw new \InvalidArgumentException('If option is given as array, it has to have a "label"-key!'); 55 $this->options[$key] = $val; 56 } elseif(is_int($key)) { 57 $this->options[$val] = array('label' => (string) $val); 58 } else { 59 $this->options[$key] = array('label' => (string) $val); 60 } 61 } 62 return $this; 63 } 64 65 66 /** 67 * The HTML representation of this element 68 * 69 * @return string 70 */ 71 public function toHTML() { 72 if ($this->attributes['label'] === null) { 73 return $this->renderOptions(); 74 } 75 $html = '<optgroup '. buildAttributes($this->attrs()) . '>'; 76 $html .= $this->renderOptions(); 77 $html .= '</optgroup>'; 78 return $html; 79 } 80 81 82 /** 83 * @return string 84 */ 85 protected function renderOptions() { 86 $html = ''; 87 foreach($this->options as $key => $val) { 88 $selected = ($key == $this->value) ? ' selected="selected"' : ''; 89 $attrs = ''; 90 if (!empty($val['attrs']) && is_array($val['attrs'])) { 91 $attrs = buildAttributes($val['attrs']); 92 } 93 $html .= '<option' . $selected . ' value="' . hsc($key) . '" '.$attrs.'>' . hsc($val['label']) . '</option>'; 94 } 95 return $html; 96 } 97} 98