6 * Dropdown input widget, wrapping a `<select>` element. Intended to be used within a
9 class DropdownInputWidget extends InputWidget {
11 * HTML `<option>` tags for this widget, as Tags.
14 protected $options = [];
17 * @param array $config Configuration options
18 * @param array[] $config['options'] Array of menu options in the format
19 * `[ 'data' => …, 'label' => … ]`
21 public function __construct( array $config = [] ) {
23 parent::__construct( $config );
26 $this->setOptions( isset( $config['options'] ) ? $config['options'] : [] );
27 $this->addClasses( [ 'oo-ui-dropdownInputWidget', 'oo-ui-dropdownInputWidget-php' ] );
28 $this->input->addClasses( [ 'oo-ui-indicator-down' ] );
31 protected function getInputElement( $config ) {
32 return new Tag( 'select' );
35 public function setValue( $value ) {
36 $this->value = $this->cleanUpValue( $value );
37 foreach ( $this->options as &$opt ) {
38 if ( $opt->getAttribute( 'value' ) === $this->value ) {
39 $opt->setAttributes( [ 'selected' => 'selected' ] );
41 $opt->removeAttributes( [ 'selected' ] );
48 * Set the options available for this input.
50 * @param array[] $options Array of menu options in the format
51 * `[ 'data' => …, 'label' => … ]`
54 public function setOptions( $options ) {
55 $value = $this->getValue();
56 $isValueAvailable = false;
58 $container = $this->input;
60 // Rebuild the dropdown menu
61 $this->input->clearContent();
62 foreach ( $options as $opt ) {
63 if ( empty( $opt['optgroup'] ) ) {
64 $optValue = $this->cleanUpValue( $opt['data'] );
65 $option = ( new Tag( 'option' ) )
66 ->setAttributes( [ 'value' => $optValue ] )
67 ->appendContent( isset( $opt['label'] ) ? $opt['label'] : $optValue );
69 if ( $value === $optValue ) {
70 $isValueAvailable = true;
72 $container->appendContent( $option );
74 $option = ( new Tag( 'optgroup' ) )
75 ->setAttributes( [ 'label' => $opt['optgroup'] ] );
76 $this->input->appendContent( $option );
80 $this->options[] = $option;
83 // Restore the previous value, or reset to something sensible
84 if ( $isValueAvailable ) {
85 // Previous value is still available
86 $this->setValue( $value );
88 // No longer valid, reset
89 if ( count( $options ) ) {
90 $this->setValue( $options[0]['data'] );
97 public function getConfig( &$config ) {
99 foreach ( $this->options as $option ) {
100 if ( $option->getTag() !== 'optgroup' ) {
101 $label = $option->content[0];
102 $data = $option->getAttribute( 'value' );
103 $o[] = [ 'data' => $data, 'label' => $label ];
105 $optgroup = $option->getAttribute( 'label' );
106 $o[] = [ 'optgroup' => $optgroup ];
109 $config['options'] = $o;
110 return parent::getConfig( $config );