1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace fieldwork\components; |
4
|
|
|
|
5
|
|
|
class Checkbox extends Field |
6
|
|
|
{ |
7
|
|
|
|
8
|
|
|
const CHECKED = 'checked'; |
9
|
|
|
|
10
|
|
|
const ON = 'on'; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Constructs a new checkbox |
14
|
|
|
* |
15
|
|
|
* @param string $slug |
16
|
|
|
* @param string $label The string to display next to the checkbox |
17
|
|
|
* @param bool $checked Whether the checkbox should be checked initially. Defaults to false |
18
|
|
|
* @param int $storeValueLocally |
19
|
|
|
*/ |
20
|
|
|
public function __construct ($slug, $label, $checked = false, $storeValueLocally = 0) |
21
|
|
|
{ |
22
|
|
|
parent::__construct($slug, $label, $checked ? self::ON : '', $storeValueLocally); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function getClasses () |
26
|
|
|
{ |
27
|
|
|
return array_merge( |
28
|
|
|
parent::getClasses(), array('checkbox') |
29
|
|
|
); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Set the "checked" state of this box |
34
|
|
|
* @param bool $checked |
35
|
|
|
*/ |
36
|
|
|
public function setChecked ($checked = true) |
37
|
|
|
{ |
38
|
|
|
$this->value = $checked ? self::ON : ''; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Is the checkbox checked in its current state? |
43
|
|
|
* @return bool |
44
|
|
|
*/ |
45
|
|
|
public function isChecked () |
46
|
|
|
{ |
47
|
|
|
return $this->value === self::ON; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function getAttributes () |
51
|
|
|
{ |
52
|
|
|
$attrs = array( |
53
|
|
|
'type' => 'checkbox', |
54
|
|
|
'value' => self::ON |
55
|
|
|
); |
56
|
|
|
if ($this->isChecked()) |
57
|
|
|
$attrs[self::CHECKED] = self::CHECKED; |
58
|
|
|
return array_merge(parent::getAttributes(), $attrs); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function getHTML ($showLabel = true) |
62
|
|
|
{ |
63
|
|
|
$label = $showLabel ? "<label for=\"" . $this->getId() . "\">" . $this->label . "</label>" : ""; |
64
|
|
|
return "<div class=\"checkbox-wrapper\"><input " . $this->getAttributesString() . ">" . $label . "</div>"; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
protected function getRestoreDefault () |
68
|
|
|
{ |
69
|
|
|
return ''; |
70
|
|
|
// override this so that the checkbox is not read as "checked" when the post var is not sent along |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|