Hello Everybody,
I have the following code in a drupal form

......
$form['anoncountry']=array(
'#type' => 'select',
'#title' => t('Country'),
'#default_value' => 'select',
'#required' => TRUE,
'#options' => $Country
);

$Country=array("Afghanistan",
"Aland Islands",....");
......

When i try to Insert it into the database using the following statement in the submitfunction I GET THE INDEX OF THE COUNTRY I.E IF I SELECT "AFGHANISTAN" THE VALUE 0 gets inserted instead of AFGHANISTAN into the Database.

function guestbook_form_entry_form_submit($form, &$form_state) {
.....
$result = db_query("INSERT INTO {test} (value1, country)
VALUES('%s', '%s')", $form_state['values']['test'], $form_state['values']['anoncountry']);
}

Can anybody tell me what am i doing Wrong? Any suggestions would be greatly appreciated.

Regards,
Judef

Comments

nevets’s picture

That would be the expected behavior. You can think of the array used for #options as having keys (indexes) and input strings. The input strings are what are shown to the user, the keys as you figured out are what is stored in the database. Generally it is more efficient to story integers and it avoids the issue of typos in a key value. You could change $Country so it uses the country for both the index and value of you might write a small help function something like

yourmodule_getcountry($index = NULL) {
   $country=array("Afghanistan",
     "Aland Islands",....");

   if ( empty($index) ) {
     return $country;
   }
   else if ( $index >= 0 & $index < count($country) ) {
      return $country[$index];
   }
   else {
       return '';
   }
}

Then in your form code set #option like '#option' => yourmodule_getcountry();

And in the code that loads records use something like $country_name = yourmodule_getcountry($index); to change the stored key to a string.

judef’s picture

Thankyou nevets for your time and code. This helped me a lot.

Regards,
Judef