0

So I've got this form:

$form['color'] = array(
        '#type' => 'select',
        '#title' => t('Kleur'),
        '#options' => array(
            0 => t('Wit'),
            1 => t('Geel'),
            2 => t('Groen'),
            3 => t('Rood'),
        ),
        '#default_value' => 'Rood',
  );

As expected, this doesn't currently set the default value to 'Rood'. How would I get it so that the default value can be accessed by it's value?

Note that this example shows the string 'Rood', but in practice it would be a variable string that is pulled from the database.

Thanks in advance!

2

Default value should point to key, not a value.

In your example, default_value should be as in below.

'#default_value' => 3,

Hope below link will help you.

https://www.drupal.org/node/240783#comment-1794710

  • Like I said, my default value comes from a database which holds the string values, so your solution won't help at all. – Neglexis Feb 11 '15 at 11:13
  • @Neglexis Just use array_search to determine the key from the value, Drupal won't have anything to help as it's just a basic language feature – Clive Feb 11 '15 at 11:26
  • @Clive, I tried array_search before, but it didn't work because my #options array doesn't seem to be fully defined when #default value is called. However, you did make me to rethink it, and defining an options array before the form seems to be the way to go :) Thanks! – Neglexis Feb 11 '15 at 11:32
  • Yep that's the one @Neglexis :) – Clive Feb 11 '15 at 11:46
0

I think you should probably use for loop to do this. Like:

// options is a array variable contains the data as 
// options[0] = "Wit"
// options[1] = "Geel"
// options[2] = "Groen"
// options[3] = "Rood"

$string = ""; // $string will come from database that you want to be default.
for($i = 0; $i < strlen(options); $i++){
  if(options[$i] == $string){
    $catch_key = $i;
  }
}

and then at form field creation time

'#default_value' => $catch_key,
  • 1
    Right idea, wrong implementation - array_search() will be quicker – Clive Feb 11 '15 at 11:26
  • array_search() sometimes not work with the values which are not in utf-8.It might be provide the wrong result with the data like Ê, Â etc – Drupal_with_Delhi Feb 11 '15 at 11:27
  • So use UTF-8 encoding :) – Clive Feb 11 '15 at 11:29

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.