xref: /plugin/struct/types/Checkbox.php (revision ee9831356b74138b1f383487fbd76c7906f6fd02)
1<?php
2namespace dokuwiki\plugin\struct\types;
3
4class Checkbox 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        return $options;
20    }
21
22    /**
23     * A single checkbox, additional values are ignored
24     *
25     * @param string $name
26     * @param string $rawvalue
27     * @param string $htmlID
28     *
29     * @return string
30     */
31    public function valueEditor($name, $rawvalue, $htmlID) {
32        $class = 'struct_' . strtolower($this->getClass());
33
34        $name = hsc($name);
35        $options = $this->getOptions();
36        $opt = array_shift($options);
37
38        if($rawvalue == $opt) {
39            $checked = 'checked="checked"';
40        } else {
41            $checked = '';
42        }
43        $opt = hsc($opt);
44        $id = !empty($htmlID) ? "id=\"$htmlID\"" : '';
45        $html = "<label><input type=\"checkbox\" name=\"$name\" class=\"$class\" value=\"$opt\" $id $checked>&nbsp;$opt</label>";
46        return $html;
47    }
48
49    /**
50     * Multiple checkboxes
51     *
52     * @param string    $name
53     * @param \string[] $rawvalues
54     * @param string    $htmlID
55     *
56     * @return string
57     */
58    public function multiValueEditor($name, $rawvalues, $htmlID) {
59        $class = 'struct_' . strtolower($this->getClass());
60
61        $name = hsc($name);
62        $html = '';
63        foreach($this->getOptions() as $opt) {
64            if(in_array($opt, $rawvalues)) {
65                $checked = 'checked="checked"';
66            } else {
67                $checked = '';
68            }
69
70            $id = !empty($htmlID) ? "id=\"$htmlID\"" : '';
71            $htmlID = null;
72
73            $opt = hsc($opt);
74            $html .= "<label><input type=\"checkbox\" name=\"{$name}[]\" class=\"$class\" value=\"$opt\" $id $checked>&nbsp;$opt</label>";
75        }
76        return $html;
77    }
78
79}
80