4

I would like to validate the company name chosen in a form in a "select" form field.

When I try $form_values['submitted_tree']['company_1']; it shows me the key instead of the string value.

I tried the following code, but it still prints '1' (the key) instead of the value associated with the key.

    $_page_num = $form_state['values']['details']['page_num'];
    $key1 = $form_state['values']['submitted_tree']['company_1'];
    $value1 = $form['submitted_tree']['company_1']['#options'][$key1];
    $key2 = $form_state['values']['submitted_tree']['company_2'];
    $value2 = $form['submitted_tree']['company_2']['#options'][$key2];

    if (($_page_num == 2) && ($value1 == $value2)) {
      drupal_set_message(print_r($form['submitted_tree']['company_2']['#options'][$key2]));
    }

Could anyone help me to retrieve the actual text value displayed in select option chosen? I have tried $form_state as well, but it returns the same result.

8

You can use the key to get the value by referencing the options array in the original form element:

$key = $form_state['values']['submitted_tree']['company_1'];
$value = $form['submitted_tree']['company_1']['#options'][$key];
3
  • Hi Clive, I tried this, but its still showing me '1' I have edited the qn, with the code I used. Kindly let me know if its fine.
    – iRiddler
    Feb 1 '12 at 22:19
  • 1
    What reported by Clive is the only way to get that value. If you are not getting a different string, probably the form field just used "1" as option value, and not array("1" => "String to show").
    – apaderno
    Feb 5 '12 at 21:52
  • note that the "submitted tree" is not a drupal standard, but reflects the structure of the op's form. For a flat form simply delete the ['submitted_tree'] bit and, of course, change ['company_1'] to your own element id. Mar 29 '14 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.