xref: /plugin/struct/types/Checkbox.php (revision 57775e30117bbc976c01a11e3ac8a5b8bd694e38)
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        $options = $this->getOptions();
33        $opt = array_shift($options);
34
35        if($rawvalue == $opt) {
36            $checked = 'checked';
37        } else {
38            $checked = '';
39        }
40        $opt = hsc($opt);
41        $params = array(
42            'name' => $name,
43            'value' => $opt,
44            'class' => 'struct_' . strtolower($this->getClass()),
45            'type' => 'checkbox',
46            'id' => $htmlID,
47            'checked' => $checked,
48        );
49        $attributes = buildAttributes($params, true);
50        return "<label><input $attributes>&nbsp;$opt</label>";
51    }
52
53    /**
54     * Multiple checkboxes
55     *
56     * @param string    $name
57     * @param \string[] $rawvalues
58     * @param string    $htmlID
59     *
60     * @return string
61     */
62    public function multiValueEditor($name, $rawvalues, $htmlID) {
63        $class = 'struct_' . strtolower($this->getClass());
64
65        $html = '';
66        foreach($this->getOptions() as $opt) {
67            if(in_array($opt, $rawvalues)) {
68                $checked = 'checked';
69            } else {
70                $checked = '';
71            }
72
73            $params = array(
74                'name' => $name . '[]',
75                'value' => $opt,
76                'class' => $class,
77                'type' => 'checkbox',
78                'id' => $htmlID,
79                'checked' => $checked,
80            );
81            $attributes = buildAttributes($params, true);
82            $htmlID = '';
83
84            $opt = hsc($opt);
85            $html .= "<label><input $attributes>&nbsp;$opt</label>";
86        }
87        return $html;
88    }
89
90}
91