-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathMulticheckboxField.php
More file actions
150 lines (126 loc) · 3.16 KB
/
MulticheckboxField.php
File metadata and controls
150 lines (126 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<?php
namespace Gregwar\Formidable\Fields;
/**
* Checkboxs
*
* @author Grégoire Passault <g.passault@gmail.com>
*/
class MulticheckboxField extends Field
{
/**
* Source name
*/
protected $source;
/**
* Checkboxes
*/
protected $checkboxes = array();
/**
* Labels
*/
protected $labels = array();
/**
* Push saving
*/
protected $pushSave = array();
public function __sleep()
{
return array_merge(parent::__sleep(), array(
'labels', 'source', 'checkboxes', 'pushSave'
));
}
public function check()
{
return;
}
public function push($var, $value = null)
{
switch ($var) {
case 'source':
$this->source = $value;
break;
default:
parent::push($var, $value);
break;
}
}
public function getSource()
{
return $this->source;
}
public function source($datas)
{
foreach ($datas as $value => $label) {
$this->checkboxes[$value] = $checkbox = new CheckboxField;
$checkbox->push('name', $this->nameFor($value));
$checkbox->push('value', '1');
$this->labels[$this->nameFor($value)] = $label;
foreach ($this->pushSave as $var => $val) {
$checkbox->push($var, $val);
}
}
}
protected function nameFor($name)
{
return $this->getName().'['.$name.']';
}
public function setValue($values, $default = false)
{
if (!is_array($values)) {
return;
}
$checked = array();
if ($this->isNumericArray($values)) {
foreach ($values as $name) {
$checked[$this->nameFor($name)] = true;
}
} else {
foreach ($values as $name => $one) {
$checked[$this->nameFor($name)] = true;
}
}
foreach ($this->checkboxes as $checkbox) {
if (isset($checked[$checkbox->getName()])) {
$checkbox->setChecked(true);
} else {
$checkbox->setChecked(false);
}
}
}
protected function isNumericArray(array $array)
{
$i = 0;
foreach (array_keys($array) as $key) {
if ($i !== $key) {
return false;
}
$i++;
}
return true;
}
public function getValue()
{
$values = array();
foreach ($this->checkboxes as $key => $checkbox) {
if ($checkbox->isChecked()) {
$values[] = $key;
}
}
return $values;
}
public function getHtml()
{
$html = '';
if ($this->checkboxes) {
foreach ($this->checkboxes as $checkbox) {
$html.= '<div class="'.$this->getAttribute('class').'">';
$html.= '<label>';
$html.= $checkbox->getHtml();
$html.= $this->labels[$checkbox->getName()];
$html.= '</label>';
$html.= '</div>';
}
}
return $html;
}
}