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