Considering that no one seems to have reported this I wonder if it's not a bug...
If I want to use the form API to create a select box with options like

<option value='1'>January</option>
<option value='1'>February</option>
<option value='1'>March</option>
<option value='2'>April</option>
<option value='2'>May</option>
<option value='2'>June</option>

the array would need to be something like

array(
 1=>'January',
 1=>'February',
 1=>'March',
 2=>'April',
 2=>'May',
 2=>'June',
)

which will not work, due to the same key being used repeatedly.

Is there a reason for having the option array work like this?

Comments

montesq’s picture

What happens if you do it? Do you get an error?
Could you provide a sample module?

berdir’s picture

Category: bug » feature

Well, I think it is simply a limitation of the API, not an actual bug. There are multiple ways around it:

- Change your select to array(1 => t('January / February / March')
- Do an internal mapping in your submit function like this.

$mapping = array(
 1 => 1,
 2 => 1,
 3 => 1,
 4 => 2,
 // ...
);

$quarter = $mapping[$form_state['values']['quarter']];

You could also provide a patch to allow a array structure like this: array(array('value' => 1, 'title' => t('January')) but this could only be added to D8 (and chances are that it won't be at all).

Changing this to a feature request...

doublejosh’s picture

Ran into the same issue while creating options for "sticky" countries above an alpha list of all countries. Same limitation of the Form API.

Looks like the only two options for quite some time are: 1) submit mapping handler - 2) theme layer solution.

mdupont’s picture

Status: Active » Closed (works as designed)

Currently Drupal relies on the key to know which value to store and display, so it is only logical that it doesn't allow duplicate keys. So if you really have to provide similar keys, then do a mapping, a parsing or a theme solution. Closing the issue.

drifter’s picture

Actually, there is a weird branch in form_select_options() that allows you to bypass this and have multiple options with the same key. It involves passing an array of object with an 'option' property.

for example:

$opt1 = new stdClass;
$opt1->option = array(1 => 'Value 1A');
$opt2 = new stdClass;
$opt2->option = array(1 => 'Value 1B');
$options = array($opt1, $opt2);

Then try setting the select form element's options to $options.

See:

https://api.drupal.org/api/drupal/includes%21form.inc/function/form_sele...

pmkanse’s picture

Issue summary: View changes

#5 works well!!! Thanks.

jmuzz’s picture

Thank you for #5.

You can use typecasting and combine with non-object options too:

$options = array(
  (object) array('option' => array('all' => 'Please choose an option')),
  '1' => 'First option',
  '2' => 'Second option',
  (object) array('option' => array('all' => 'Everything')),
);