Skip to content

Unable to set default selected options in multiple select - Fix Provided #39

Description

@anthony-brindley

First of all - amazing work! Thank you so much!

Just working through a situation where I have a multi-select and I am unable to set default selected options. I've used it in the same way as you would on a standard select box and the settings screen loads fine, but just doesn't select anything.

So, I've fixed the issue and it turns out the default wasn't being set for a standard selects either. Here's the fix I implemented and I hope it's something you can test and add to your codebase?

//RationalOptionPages.php Line 475
// we need to add an extra 'else' statement inside the foreach loop for when the select DOESN'T have any options set - i.e it's not been updated yet. Whole revised foreach loop code below. Also removed the unnecessary '$selected' variable on Line 476

foreach ( $field['choices'] as $value => $text ) {

  if ( isset( $this->options[ $field['id'] ] ) ) {
      if (!is_array($this->options[ $field['id'] ] ) ) {
	      $selected = $value === $this->options[ $field['id'] ] ? 'selected="selected"' : '';
      } else 
      {
	      $selected = in_array( $value, $this->options[ $field['id'] ] ) ? 'selected="selected"' : '';
      }
  } else
  {
      if(is_array($field['value']))
      {
         $selected = (in_array($value, $field['value'])) ? 'selected="selected"' : '';
      } else
      {
	      $selected = $value === $field['value'] ? 'selected="selected"' : '';
      }
}
    printf('<option %s value="%s">%s</option>',
        $selected,																			// selected
        $value,																				// value
        __($text,'text-domain')                                                                                                                                 // text
    );
}

// end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions