Checkbox.php
1.92 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
<?php
namespace AC\Form\Element;
use AC\Form\Element;
class Checkbox extends Element {
/**
* @var bool
*/
protected $vertical;
protected $multiple;
protected function get_type() {
return 'checkbox';
}
protected function get_classes() {
$classes = [
$this->get_type() . '-labels',
];
if ( $this->is_vertical() ) {
$classes[] = 'vertical';
}
return $classes;
}
public function render() {
$elements = $this->get_elements();
if ( ! $elements ) {
return false;
}
$template = '<div class="%s">%s</div>';
return sprintf( $template, implode( ' ', $this->get_classes() ), implode( "\n", $elements ) );
}
private function get_elements() {
if ( $this->is_multiple() ) {
$this->set_name( $this->get_name() . '[]' );
}
$options = $this->get_options();
if ( empty( $options ) ) {
return null;
}
$elements = [];
$value = (array) $this->get_value();
foreach ( $options as $key => $label ) {
$input = new Input( $this->get_name() );
$input->set_value( $key )
->set_type( $this->get_type() )
->set_id( $this->get_id() . '-' . $key );
if ( in_array( $key, $value ) ) {
$input->set_attribute( 'checked', 'checked' );
}
$attributes = $this->get_attributes();
$elements[] = sprintf( '<label %s>%s%s</label>', $this->get_attributes_as_string( $attributes ), $input->render(), $label );
}
if ( $description = $this->render_description() ) {
$elements[] = $description;
}
return $elements;
}
public function set_multiple( $multiple ) {
$this->multiple = (bool) $multiple;
return $this;
}
public function is_multiple() {
if ( empty( $this->multiple ) ) {
return false;
}
return $this->multiple;
}
public function set_vertical( $vertical ) {
$this->vertical = (bool) $vertical;
return $this;
}
public function is_vertical() {
if ( empty( $this->vertical ) ) {
return false;
}
return $this->vertical;
}
}