1<?php
2
3namespace dokuwiki\plugin\struct\types;
4
5class Dropdown extends AbstractBaseType
6{
7    protected $config = [
8        'values' => 'one, two, three',
9        'combobox' => false,
10    ];
11
12    /**
13     * Creates the options array
14     *
15     * @return array
16     */
17    protected function getOptions()
18    {
19        $options = explode(',', $this->config['values']);
20        $options = array_map('trim', $options);
21        $options = array_filter($options);
22        array_unshift($options, '');
23        $options = array_combine($options, $options);
24        return $options;
25    }
26
27    /**
28     * A Dropdown with a single value to pick
29     *
30     * @param string $name
31     * @param string $rawvalue
32     * @return string
33     */
34    public function valueEditor($name, $rawvalue, $htmlID)
35    {
36        $params = [
37            'name' => $name,
38            'class' => 'struct_' . strtolower($this->getClass()),
39            'id' => $htmlID
40        ];
41        $attributes = buildAttributes($params, true);
42        $html = "<select $attributes>";
43        foreach ($this->getOptions() as $opt => $val) {
44            if ($opt == $rawvalue) {
45                $selected = 'selected="selected"';
46            } else {
47                $selected = '';
48            }
49
50            $html .= "<option $selected value=\"" . hsc($opt) . "\">" . hsc($val) . '</option>';
51        }
52        $html .= '</select>';
53
54        if ($this->config['combobox']) {
55            $html = "<vanilla-combobox>$html</vanilla-combobox>";
56        }
57
58        return $html;
59    }
60
61    /**
62     * A dropdown that allows to pick multiple values
63     *
64     * @param string $name
65     * @param \string[] $rawvalues
66     * @param string $htmlID
67     *
68     * @return string
69     */
70    public function multiValueEditor($name, $rawvalues, $htmlID)
71    {
72        $params = [
73            'name' => $name . '[]',
74            'class' => 'struct_' . strtolower($this->getClass()),
75            'multiple' => 'multiple',
76            'size' => '5',
77            'id' => $htmlID
78        ];
79        $attributes = buildAttributes($params, true);
80        $html = "<select $attributes>";
81        foreach ($this->getOptions() as $raw => $opt) {
82            if (in_array($raw, $rawvalues)) {
83                $selected = 'selected="selected"';
84            } else {
85                $selected = '';
86            }
87
88            $html .= "<option $selected value=\"" . hsc($raw) . "\">" . hsc($opt) . '</option>';
89        }
90        $html .= '</select> ';
91        $html .= '<small>' . $this->getLang('multidropdown') . '</small>';
92
93        if ($this->config['combobox']) {
94            $html = "<vanilla-combobox>$html</vanilla-combobox>";
95        }
96
97        return $html;
98    }
99}
100