3 namespace dokuwiki\Form
;
5 class OptGroup
extends Element
7 protected $options = [];
8 protected $values = [];
11 * @param string $label The label text for this element (will be autoescaped)
12 * @param array $options The available options
14 public function __construct($label, $options)
16 parent
::__construct('optGroup', ['label' => $label]);
17 $this->options($options);
21 * Store the given values so they can be used during rendering
23 * This is intended to be only called from within DropdownElement::val()
25 * @param string[] $values the values to set
26 * @return string[] the values that have been set (options exist)
27 * @see DropdownElement::val()
29 public function storeValues($values)
32 foreach ($values as $value) {
33 if (isset($this->options
[$value])) {
34 $this->values
[] = $value;
42 * Get or set the options of the optgroup
44 * Options can be given as associative array (value => label) or as an
45 * indexd array (label = value) or as an array of arrays. In the latter
46 * case an element has to look as follows:
47 * option-value => array (
48 * 'label' => option-label,
50 * attr-key => attr-value, ...
54 * @param null|array $options
57 public function options($options = null)
59 if ($options === null) return $this->options
;
60 if (!is_array($options)) throw new \
InvalidArgumentException('Options have to be an array');
62 foreach ($options as $key => $val) {
64 if (!array_key_exists('label', $val)) {
65 throw new \
InvalidArgumentException(
66 'If option is given as array, it has to have a "label"-key!'
70 array_key_exists('attrs', $val) &&
71 is_array($val['attrs']) &&
72 array_key_exists('selected', $val['attrs'])
74 throw new \
InvalidArgumentException(
75 'Please use function "DropdownElement::val()" to set the selected option'
78 $this->options
[$key] = $val;
79 } elseif (is_int($key)) {
80 $this->options
[$val] = ['label' => (string)$val];
82 $this->options
[$key] = ['label' => (string)$val];
89 * The HTML representation of this element
93 public function toHTML()
95 if ($this->attributes
['label'] === null) {
96 return $this->renderOptions();
98 $html = '<optgroup ' . buildAttributes($this->attrs()) . '>';
99 $html .= $this->renderOptions();
100 $html .= '</optgroup>';
107 protected function renderOptions()
110 foreach ($this->options
as $key => $val) {
111 $selected = in_array((string)$key, $this->values
) ?
' selected="selected"' : '';
113 if (!empty($val['attrs']) && is_array($val['attrs'])) {
114 $attrs = buildAttributes($val['attrs']);
116 $html .= '<option' . $selected . ' value="' . hsc($key) . '" ' . $attrs . '>';
117 $html .= hsc($val['label']);
118 $html .= '</option>';