1
|
|
|
<?php |
2
|
|
|
namespace Rocket\UI\Forms\Fields; |
3
|
|
|
|
4
|
|
|
use Illuminate\Support\Collection; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Adds a checkbox |
8
|
|
|
* |
9
|
|
|
* @method $this checked(boolean $checked) |
10
|
|
|
*/ |
11
|
|
|
class Checkbox extends Field |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Override the constructor for some options |
15
|
|
|
*/ |
16
|
|
|
public function __construct($id, $data = []) |
17
|
|
|
{ |
18
|
|
|
$this->type = 'checkbox'; |
19
|
|
|
|
20
|
|
|
parent::__construct($id, $data); |
21
|
|
|
|
22
|
|
|
if (!array_key_exists('check_value', $this->params)) { |
23
|
|
|
$this->params['check_value'] = 'on'; |
24
|
|
|
} |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Adds some attributes |
29
|
|
|
*/ |
30
|
|
|
protected function inputAttributes() |
31
|
|
|
{ |
32
|
|
|
$this->input_attributes['id'] = $this->id; |
33
|
|
|
$this->input_attributes['name'] = $this->name; |
34
|
|
|
$this->input_attributes['type'] = 'checkbox'; |
35
|
|
|
$this->input_attributes['class'] = ['checkbox']; //removes elm |
36
|
|
|
|
37
|
|
|
$this->input_attributes['value'] = $this->params['check_value']; |
38
|
|
|
|
39
|
|
|
if ($this->getCheckboxCheckedState()) { |
40
|
|
|
$this->input_attributes['checked'] = 'checked'; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$this->params['label_position'] = 'after'; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Get the check state for a checkbox input. |
48
|
|
|
* |
49
|
|
|
* @return bool |
50
|
|
|
*/ |
51
|
|
|
protected function getCheckboxCheckedState() |
52
|
|
|
{ |
53
|
|
|
$value = $this->input_attributes['value']; |
54
|
|
|
$default = array_key_exists('checked', $this->params) ? $this->params['checked'] : false; |
55
|
|
|
$current = $this->getValidator()->getValue($this->name, $default); |
56
|
|
|
|
57
|
|
|
if (is_array($current)) { |
58
|
|
|
return in_array($value, $current); |
59
|
|
|
} elseif ($current instanceof Collection) { |
60
|
|
|
return $current->contains('id', $value); |
61
|
|
|
} else { |
62
|
|
|
return (bool) $current; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function classes() |
67
|
|
|
{ |
68
|
|
|
parent::classes(); |
69
|
|
|
|
70
|
|
|
$this->label_attributes['class'][] = 'checkbox'; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|