xref: /plugin/struct/types/Checkbox.php (revision 7234bfb14e712ff548d9266ef32fdcc8eaf2d04e)
1<?php
2
3namespace dokuwiki\plugin\struct\types;
4
5class Checkbox extends AbstractBaseType
6{
7    protected $config = ['values' => 'one, two, three'];
8
9    /**
10     * Creates the options array
11     *
12     * @return array
13     */
14    protected function getOptions()
15    {
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    {
33        $options = $this->getOptions();
34        $opt = array_shift($options);
35
36        if ($rawvalue == $opt) {
37            $checked = 'checked';
38        } else {
39            $checked = '';
40        }
41        $opt = hsc($opt);
42        $params = ['name' => $name, 'value' => $opt, 'class' => 'struct_' . strtolower($this->getClass()), 'type' => 'checkbox', 'id' => $htmlID, 'checked' => $checked];
43        $attributes = buildAttributes($params, true);
44        return "<label><input $attributes>&nbsp;$opt</label>";
45    }
46
47    /**
48     * Multiple checkboxes
49     *
50     * @param string $name
51     * @param \string[] $rawvalues
52     * @param string $htmlID
53     *
54     * @return string
55     */
56    public function multiValueEditor($name, $rawvalues, $htmlID)
57    {
58        $class = 'struct_' . strtolower($this->getClass());
59
60        $html = '';
61        foreach ($this->getOptions() as $opt) {
62            if (in_array($opt, $rawvalues)) {
63                $checked = 'checked';
64            } else {
65                $checked = '';
66            }
67
68            $params = ['name' => $name . '[]', 'value' => $opt, 'class' => $class, 'type' => 'checkbox', 'id' => $htmlID, 'checked' => $checked];
69            $attributes = buildAttributes($params, true);
70            $htmlID = '';
71
72            $opt = hsc($opt);
73            $html .= "<label><input $attributes>&nbsp;$opt</label>";
74        }
75        return $html;
76    }
77}
78