I'm using the drupal forms api and love it but I'm having a problem setting the default value for a select box (in this case the box contains a list of country names).

Here is the snippet where I try to set the default value:

$form[$school->counter]['country'] = array(
'#type' => 'select',
'#title' => t('Country'),
'#default_value' => variable_get('country',$school->country),
'#options' => $country_disp,
);

When this is executed I get a list dropdown list of countries (which is correct), but no default value.

I have verified that $school->country contains the name of the country that should be selected.

Maybe I'm using variable_get wrong?

Comments

gpk’s picture

What does $country_disp look like, and what might $school->country look like? I suspect the latter isn't correctly corresponding with one of the elements of $country_disp. You might need to key the array $country_disp and (if necessary) convert $school->country to the relevant key. Alternatively there might be some sort of a type mismatch, though I doubt that's the problem.

gpk
----
www.gelst.com

sifuhall’s picture

Thanks for the reply.

country_disp just consists of an array of country names (in alphabetic order).

It is populated like this:

$countries = db_query("select name from dl_countries order by name" );
while ($country = db_fetch_object($countries)) {
$country_disp[] = $country->name;
}

$school->country contains the name of the country (like 'United States', or 'Bulgaria', etc.)

so how should I change this?

gpk’s picture

Maybe try

'#default_value' => array_search(variable_get('country',$school->country), $country_disp)

My thinking is that since $country_disp and hence #options is keyed by integers starting at 0, this is what you need to pass as the #default_value. Guessing though...

For info: http://uk2.php.net/manual/en/function.array-search.php

gpk
----
www.gelst.com

sifuhall’s picture

Thank you for the great solution!

It works great!