Completed
Push — master ( 089ad5...045fb9 )
by Richard
10:39
created

Checkbox::renderValidationJS()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 18

Duplication

Lines 23
Ratio 100 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 23
loc 23
ccs 15
cts 15
cp 1
rs 8.7972
c 1
b 0
f 0
cc 4
eloc 18
nc 4
nop 0
crap 4
1
<?php
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
namespace Xoops\Form;
13
14
/**
15
 * Checkbox - a checkbox form element
16
 *
17
 * @category  Xoops\Form\Checkbox
18
 * @package   Xoops\Form
19
 * @author    Kazumi Ono <[email protected]>
20
 * @author    Skalpa Keo <[email protected]>
21
 * @author    Taiwen Jiang <[email protected]>
22
 * @copyright 2001-2015 XOOPS Project (http://xoops.org)
23
 * @license   GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
24
 * @link      http://xoops.org
25
 */
26
class Checkbox extends OptionElement
27
{
28
    /**
29
     * pre-selected values in array
30
     *
31
     * @var array
32
     */
33
    protected $value = array();
34
35
    /**
36
     * Constructor
37
     *
38
     * @param string|array $caption Caption or array of all attributes
39
     *                               Control attributes:
40
     *                                   :inline true to render with inline style
41
     * @param string       $name    element name
42
     * @param mixed        $value   value(s) to be set on display, either one value or an array of them.
43
     * @param boolean      $inline  true for inline arrangement
44
     */
45 1 View Code Duplication
    public function __construct($caption, $name = null, $value = null, $inline = true)
46
    {
47 1
        if (is_array($caption)) {
48 1
            parent::__construct($caption);
49 1
            $this->setIfNotSet(':inline', true);
50
        } else {
51 1
            parent::__construct([]);
52 1
            $this->setWithDefaults('caption', $caption, '');
53 1
            $this->setWithDefaults('name', $name, 'name_error');
54 1
            $this->set('value', $value);
55 1
            $this->set(':inline', $inline);
56
        }
57 1
        $this->set('type', 'checkbox');
58 1
    }
59
60
    /**
61
     * prepare HTML for output
62
     *
63
     * @return string
64
     */
65 3
    public function render()
66
    {
67 3
        $required = $this->has('required');
68 3
        $elementOptions = $this->getOptions();
69 3
        $elementValue = $this->getValue();
70 3
        if (!is_array($elementValue)) {
71 3
            $elementValue = (array) $elementValue;
72
        }
73 3
        $extra = ($this->getExtra() != '' ? " " . $this->getExtra() : '');
74
75 3
        $elementName = $this->getName();
76 3
        $elementId = $elementName;
77 3
        if (count($elementOptions) > 1 && substr($elementName, -2, 2) !== '[]') {
78 2
            $elementName = $elementName . '[]';
79 2
            $this->setName($elementName);
80
            // If required is set, all checkboxes will be required by the browser,
81
            // which is not usually useful. We stash the value of required above
82
            // and unset now. We restore it before return so JS validation will still
83
            // be triggered. This is only a problem if there is more than one checkbox.
84 2
            $this->remove('required');
85
        }
86
87 3
        $ret = "";
88 3
        $idCount = 0;
89 3
        foreach ($elementOptions as $value => $name) {
90 2
            $this->remove('checked');
91 2
            if (!empty($elementValue) && in_array($value, $elementValue)) {
92 1
                $this->set('checked');
93
            }
94 2
            $this->set('value', $value);
95 2
            ++$idCount;
96 2
            $this->set('id', $elementId . $idCount);
97 2
            $ret .= '<label class="checkbox' . ((bool) $this->get(':inline', false) ? ' inline' : '') . '">' . "\n";
98 2
            $ret .= '<input ' . $this->renderAttributeString() . $extra . '>' . "\n";
99 2
            $ret .= $name . "\n";
100 2
            $ret .= "</label>" . "\n";
101
        }
102 3
        if ($required) {
103 1
            $this->set('required');
104
        }
105 3
        return $ret;
106
    }
107
108
    /**
109
     * Render custom javascript validation code
110
     *
111
     * @return string
112
     */
113 2 View Code Duplication
    public function renderValidationJS()
114
    {
115
        // render custom validation code if any
116 2
        if (!empty($this->customValidationCode)) {
117
            return implode("\n", $this->customValidationCode);
118
            // generate validation code if required
119 2
        } elseif ($this->isRequired()) {
120 1
            $eltname = $this->getName();
121 1
            $eltcaption = $this->getCaption();
122 1
            $eltmsg = empty($eltcaption)
123
                ? sprintf(\XoopsLocale::F_ENTER, $eltname)
124 1
                : sprintf(\XoopsLocale::F_ENTER, $eltcaption);
125 1
            $eltmsg = str_replace('"', '\"', stripslashes($eltmsg));
126
            return "\n"
127 1
            . "var hasChecked = false; var checkBox = myform.elements['{$eltname}'];"
128 1
            . " if (checkBox.length) {for (var i = 0; i < checkBox.length; i++)"
129 1
            . " {if (checkBox[i].checked == true) {hasChecked = true; break;}}}"
130 1
            . "else{if (checkBox.checked == true) {hasChecked = true;}}"
131 1
            . "if (!hasChecked) {window.alert(\"{$eltmsg}\");if (checkBox.length)"
132 1
            . " {checkBox[0].focus();}else{checkBox.focus();}return false;}";
133
        }
134 1
        return '';
135
    }
136
}
137