Select.php
101 lines
| 1 | <?php |
| 2 | |
| 3 | if ( ! defined( 'ABSPATH' ) ) { |
| 4 | exit; |
| 5 | } |
| 6 | |
| 7 | class AC_Form_Element_Select extends AC_Form_Element { |
| 8 | |
| 9 | /** |
| 10 | * @var string |
| 11 | */ |
| 12 | protected $no_result = ''; |
| 13 | |
| 14 | protected function render_options( array $options ) { |
| 15 | $output = array(); |
| 16 | |
| 17 | foreach ( $options as $key => $option ) { |
| 18 | if ( isset( $option['options'] ) && is_array( $option['options'] ) ) { |
| 19 | $output[] = $this->render_optgroup( $option ); |
| 20 | |
| 21 | continue; |
| 22 | } |
| 23 | |
| 24 | $output[] = $this->render_option( $key, $option ); |
| 25 | } |
| 26 | |
| 27 | return implode( "\n", $output ); |
| 28 | } |
| 29 | |
| 30 | protected function render_option( $key, $label ) { |
| 31 | $template = '<option %s>%s</option>'; |
| 32 | $attributes = $this->get_option_attributes( $key ); |
| 33 | |
| 34 | return sprintf( $template, $this->get_attributes_as_string( $attributes ), esc_html( $label ) ); |
| 35 | } |
| 36 | |
| 37 | protected function get_option_attributes( $key ) { |
| 38 | $attributes = array(); |
| 39 | $attributes['value'] = $key; |
| 40 | |
| 41 | if ( selected( $this->get_value(), $key, false ) ) { |
| 42 | $attributes['selected'] = 'selected'; |
| 43 | } |
| 44 | |
| 45 | return $attributes; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * @param array $group |
| 50 | * |
| 51 | * @return string |
| 52 | */ |
| 53 | protected function render_optgroup( array $group ) { |
| 54 | $template = '<optgroup %s>%s</optgroup>'; |
| 55 | $attributes = array(); |
| 56 | |
| 57 | if ( isset( $group['title'] ) ) { |
| 58 | $attributes['label'] = esc_attr( $group['title'] ); |
| 59 | } |
| 60 | |
| 61 | return sprintf( $template, $this->get_attributes_as_string( $attributes ), $this->render_options( $group['options'] ) ); |
| 62 | } |
| 63 | |
| 64 | public function render() { |
| 65 | if ( ! $this->get_options() ) { |
| 66 | return $this->get_no_result(); |
| 67 | } |
| 68 | |
| 69 | $template = ' |
| 70 | <select %s> |
| 71 | %s |
| 72 | </select> |
| 73 | %s'; |
| 74 | |
| 75 | $attributes = $this->get_attributes(); |
| 76 | $attributes['name'] = $this->get_name(); |
| 77 | $attributes['id'] = $this->get_id(); |
| 78 | |
| 79 | return sprintf( $template, $this->get_attributes_as_string( $attributes ), $this->render_options( $this->get_options() ), $this->render_description() ); |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * @return string |
| 84 | */ |
| 85 | public function get_no_result() { |
| 86 | return $this->no_result; |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * @param string $no_result |
| 91 | * |
| 92 | * @return $this |
| 93 | */ |
| 94 | public function set_no_result( $no_result ) { |
| 95 | $this->no_result = (string) $no_result; |
| 96 | |
| 97 | return $this; |
| 98 | } |
| 99 | |
| 100 | } |
| 101 |