xref: /plugin/struct/types/Checkbox.php (revision 5b808f9f3f75388ac6c41d0df9054f222dd3b92b)
1<?php
2
3namespace dokuwiki\plugin\struct\types;
4
5class Checkbox extends AbstractBaseType
6{
7
8    protected $config = array(
9        'values' => 'one, two, three',
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        return $options;
23    }
24
25    /**
26     * A single checkbox, additional values are ignored
27     *
28     * @param string $name
29     * @param string $rawvalue
30     * @param string $htmlID
31     *
32     * @return string
33     */
34    public function valueEditor($name, $rawvalue, $htmlID)
35    {
36        $options = $this->getOptions();
37        $opt = array_shift($options);
38
39        if ($rawvalue == $opt) {
40            $checked = 'checked';
41        } else {
42            $checked = '';
43        }
44        $opt = hsc($opt);
45        $params = array(
46            'name' => $name,
47            'value' => $opt,
48            'class' => 'struct_' . strtolower($this->getClass()),
49            'type' => 'checkbox',
50            'id' => $htmlID,
51            'checked' => $checked,
52        );
53        $attributes = buildAttributes($params, true);
54        return "<label><input $attributes>&nbsp;$opt</label>";
55    }
56
57    /**
58     * Multiple checkboxes
59     *
60     * @param string    $name
61     * @param \string[] $rawvalues
62     * @param string    $htmlID
63     *
64     * @return string
65     */
66    public function multiValueEditor($name, $rawvalues, $htmlID)
67    {
68        $class = 'struct_' . strtolower($this->getClass());
69
70        $html = '';
71        foreach ($this->getOptions() as $opt) {
72            if (in_array($opt, $rawvalues)) {
73                $checked = 'checked';
74            } else {
75                $checked = '';
76            }
77
78            $params = array(
79                'name' => $name . '[]',
80                'value' => $opt,
81                'class' => $class,
82                'type' => 'checkbox',
83                'id' => $htmlID,
84                'checked' => $checked,
85            );
86            $attributes = buildAttributes($params, true);
87            $htmlID = '';
88
89            $opt = hsc($opt);
90            $html .= "<label><input $attributes>&nbsp;$opt</label>";
91        }
92        return $html;
93    }
94}
95