Hello everyone.

I'm trying to get the displayed name from a select list using the form API. I know how to get the id or key value, it's the visible name I'm after. Anyone have any ideas?

e.g. In this example I can get the 0,1,2 from the select box using the $form_state['values']['select'] it's the option1, option2, option3 that I want to get.


$options[0] = 'option1';
$options[1] = 'option2';
$options[2] = 'option3';

$form['select'] = array(
    '#type' => 'select',
    '#title' => t('Select'),
    '#options' => $options,
    '#multiple' => FALSE,
  );

$value = $form_state['values']['select'];

Thanks very much.

Comments

roper.’s picture

$key = $form_state['values']['select'];
$title = $options[$key];

No..?

DrupalChimp’s picture

ok
Thanks.
This only works for unique keys. I wanted to have a select element with duplicated key values, but it seems that the drupal form api doesn't allow it anyway. So I'm going to have to scrap that idea.

For anyone who is interested I did find another way to do this. This will return the visible option not the id

$name = $form['select']['#options'][$form_state['values']['select']];

Thanks

roper.’s picture

Glad this worked out... Just wanted to say though, it's not the Drupal FAPI that won't allow duplicate keys, that's simply how associative arrays work. You cannot have two of the same key, the second one will override the first. :)

Aaron23’s picture

$name = $form['select']['#options'][$form_state['values']['select']];
Perfect solution...Thanks