Checkbox.php
111 lines
| 1 | <?php |
| 2 | |
| 3 | if ( ! defined( 'ABSPATH' ) ) { |
| 4 | exit; |
| 5 | } |
| 6 | |
| 7 | class AC_Form_Element_Checkbox extends AC_Form_Element { |
| 8 | |
| 9 | /** |
| 10 | * @var bool |
| 11 | */ |
| 12 | protected $vertical; |
| 13 | |
| 14 | protected $multiple; |
| 15 | |
| 16 | protected function get_type() { |
| 17 | return 'checkbox'; |
| 18 | } |
| 19 | |
| 20 | protected function get_classes() { |
| 21 | $classes = array( |
| 22 | $this->get_type() . '-labels', |
| 23 | ); |
| 24 | |
| 25 | if ( $this->is_vertical() ) { |
| 26 | $classes[] = 'vertical'; |
| 27 | } |
| 28 | |
| 29 | return $classes; |
| 30 | } |
| 31 | |
| 32 | public function render() { |
| 33 | $elements = $this->get_elements(); |
| 34 | |
| 35 | if ( ! $elements ) { |
| 36 | return false; |
| 37 | } |
| 38 | |
| 39 | $template = '<div class="%s-labels %s">%s</div>'; |
| 40 | |
| 41 | return sprintf( $template, $this->get_type(), implode( ' ', $this->get_classes() ), implode( "\n", $elements ) ); |
| 42 | } |
| 43 | |
| 44 | private function get_elements() { |
| 45 | if ( $this->is_multiple() ) { |
| 46 | $this->set_name( $this->get_name() . '[]' ); |
| 47 | } |
| 48 | |
| 49 | $options = $this->get_options(); |
| 50 | |
| 51 | if ( empty( $options ) ) { |
| 52 | return null; |
| 53 | } |
| 54 | |
| 55 | $elements = array(); |
| 56 | |
| 57 | $value = (array) $this->get_value(); |
| 58 | |
| 59 | foreach ( $options as $key => $label ) { |
| 60 | $input = new AC_Form_Element_Input( $this->get_name() ); |
| 61 | |
| 62 | $input->set_value( $key ) |
| 63 | ->set_type( $this->get_type() ) |
| 64 | ->set_id( $this->get_id() . '-' . $key ); |
| 65 | |
| 66 | if ( in_array( $key, $value ) ) { |
| 67 | $input->set_attribute( 'checked', 'checked' ); |
| 68 | } |
| 69 | |
| 70 | $attributes = $this->get_attributes(); |
| 71 | |
| 72 | $elements[] = sprintf( '<label %s>%s%s</label>', $this->get_attributes_as_string( $attributes ), $input->render(), esc_html( $label ) ); |
| 73 | } |
| 74 | |
| 75 | if ( $description = $this->render_description() ) { |
| 76 | $elements[] = $description; |
| 77 | } |
| 78 | |
| 79 | return $elements; |
| 80 | } |
| 81 | |
| 82 | public function set_multiple( $multiple ) { |
| 83 | $this->multiple = (bool) $multiple; |
| 84 | |
| 85 | return $this; |
| 86 | } |
| 87 | |
| 88 | public function is_multiple() { |
| 89 | if ( empty( $this->multiple ) ) { |
| 90 | return false; |
| 91 | } |
| 92 | |
| 93 | return $this->multiple; |
| 94 | } |
| 95 | |
| 96 | public function set_vertical( $vertical ) { |
| 97 | $this->vertical = (bool) $vertical; |
| 98 | |
| 99 | return $this; |
| 100 | } |
| 101 | |
| 102 | public function is_vertical() { |
| 103 | if ( empty( $this->vertical ) ) { |
| 104 | return false; |
| 105 | } |
| 106 | |
| 107 | return $this->vertical; |
| 108 | } |
| 109 | |
| 110 | } |
| 111 |