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
Comment #1
montesq commentedWhat happens if you do it? Do you get an error?
Could you provide a sample module?
Comment #2
berdirWell, 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.
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...
Comment #3
doublejosh commentedRan 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.
Comment #4
mdupontCurrently 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.
Comment #5
drifter commentedActually, 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:
Then try setting the select form element's options to $options.
See:
https://api.drupal.org/api/drupal/includes%21form.inc/function/form_sele...
Comment #6
pmkanse commented#5 works well!!! Thanks.
Comment #7
jmuzz commentedThank you for #5.
You can use typecasting and combine with non-object options too: