1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Xoops\Form;
13:
14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:
26: class Checkbox extends OptionElement
27: {
28: 29: 30: 31: 32:
33: protected $value = array();
34:
35: 36: 37: 38: 39: 40: 41: 42: 43: 44:
45: public function __construct($caption, $name = null, $value = null, $inline = true)
46: {
47: if (is_array($caption)) {
48: parent::__construct($caption);
49: $this->setIfNotSet(':inline', true);
50: } else {
51: parent::__construct([]);
52: $this->setWithDefaults('caption', $caption, '');
53: $this->setWithDefaults('name', $name, 'name_error');
54: $this->set('value', $value);
55: $this->set(':inline', $inline);
56: }
57: $this->set('type', 'checkbox');
58: }
59:
60: 61: 62: 63: 64:
65: public function render()
66: {
67: $required = $this->has('required');
68: $elementOptions = $this->getOptions();
69: $elementValue = $this->getValue();
70: if (!is_array($elementValue)) {
71: $elementValue = (array) $elementValue;
72: }
73: $extra = ($this->getExtra() != '' ? " " . $this->getExtra() : '');
74:
75: $elementName = $this->getName();
76: $elementId = $elementName;
77: if (count($elementOptions) > 1 && substr($elementName, -2, 2) !== '[]') {
78: $elementName = $elementName . '[]';
79: $this->setName($elementName);
80:
81:
82:
83:
84: $this->remove('required');
85: }
86:
87: $ret = "";
88: $idCount = 0;
89: foreach ($elementOptions as $value => $name) {
90: $this->remove('checked');
91: if (!empty($elementValue) && in_array($value, $elementValue)) {
92: $this->set('checked');
93: }
94: $this->set('value', $value);
95: ++$idCount;
96: $this->set('id', $elementId . $idCount);
97: $ret .= '<label class="checkbox' . ((bool) $this->get(':inline', false) ? ' inline' : '') . '">' . "\n";
98: $ret .= '<input ' . $this->renderAttributeString() . $extra . '>' . "\n";
99: $ret .= $name . "\n";
100: $ret .= "</label>" . "\n";
101: }
102: if ($required) {
103: $this->set('required');
104: }
105: return $ret;
106: }
107:
108: 109: 110: 111: 112:
113: public function renderValidationJS()
114: {
115:
116: if (!empty($this->customValidationCode)) {
117: return implode("\n", $this->customValidationCode);
118:
119: } elseif ($this->isRequired()) {
120: $eltname = $this->getName();
121: $eltcaption = $this->getCaption();
122: $eltmsg = empty($eltcaption)
123: ? sprintf(\XoopsLocale::F_ENTER, $eltname)
124: : sprintf(\XoopsLocale::F_ENTER, $eltcaption);
125: $eltmsg = str_replace('"', '\"', stripslashes($eltmsg));
126: return "\n"
127: . "var hasChecked = false; var checkBox = myform.elements['{$eltname}'];"
128: . " if (checkBox.length) {for (var i = 0; i < checkBox.length; i++)"
129: . " {if (checkBox[i].checked == true) {hasChecked = true; break;}}}"
130: . "else{if (checkBox.checked == true) {hasChecked = true;}}"
131: . "if (!hasChecked) {window.alert(\"{$eltmsg}\");if (checkBox.length)"
132: . " {checkBox[0].focus();}else{checkBox.focus();}return false;}";
133: }
134: return '';
135: }
136: }
137: