1<?php
2
3namespace dokuwiki\Form;
4
5/**
6 * Class CheckableElement
7 *
8 * For Radio- and Checkboxes
9 *
10 * @package dokuwiki\Form
11 */
12class CheckableElement extends InputElement
13{
14    /**
15     * @param string $type The type of this element
16     * @param string $name The name of this form element
17     * @param string $label The label text for this element
18     */
19    public function __construct($type, $name, $label)
20    {
21        parent::__construct($type, $name, $label);
22        // default value is 1
23        $this->attr('value', 1);
24    }
25
26    /**
27     * Handles the useInput flag and sets the checked attribute accordingly
28     */
29    protected function prefillInput()
30    {
31        global $INPUT;
32        [$name, $key] = $this->getInputName();
33        $myvalue = $this->val();
34
35        if (!$INPUT->has($name)) return;
36
37        if ($key === null) {
38            // no key - single value
39            $value = $INPUT->str($name);
40            if ($value == $myvalue) {
41                $this->attr('checked', 'checked');
42            } else {
43                $this->rmattr('checked');
44            }
45        } else {
46            // we have an array, there might be several values in it
47            $input = $INPUT->arr($name);
48            if (isset($input[$key])) {
49                $this->rmattr('checked');
50
51                // values seem to be in another sub array
52                if (is_array($input[$key])) {
53                    $input = $input[$key];
54                }
55
56                foreach ($input as $value) {
57                    if ($value == $myvalue) {
58                        $this->attr('checked', 'checked');
59                    }
60                }
61            }
62        }
63    }
64
65    /**
66     * The HTML representation of this element wrapped in a label
67     * Note: allow HTML tags in label text
68     *
69     * @return string
70     */
71    public function toHTML()
72    {
73        if ($this->label) {
74            return '<label ' . buildAttributes($this->label->attrs()) . '>' . DOKU_LF
75                . $this->mainElementHTML() . DOKU_LF
76                . '<span>' . $this->label->val() . '</span>' . DOKU_LF
77                . '</label>';
78        } else {
79            return $this->mainElementHTML();
80        }
81    }
82}
83