I use the code below to get all the categories from the am_category table into a dropdownbox in a form. It works. But when submitting the form I need the category.ID and not the name. How does one usually work with lookup tables like this one?
$category_result = db_query("SELECT id, name FROM {am_category}");
$categories = array();
foreach($category_result as $row)
{
$categories[$row->id] = t($row->name);
}
$form['category_options'] = array(
'#type' => 'value',
'#value' => $categories
);
$form['category']['category'] = array(
'#title' => t('Category'),
'#type' => 'select',
'#description' => t('Please select the category of this achievement.'),
'#options' => $form['category_options']['#value']
);
The value passed through to the
$form_statearray in your submit function will be the ID and not the name, it will be the key of the options in the drop down, not the value.If you want to shorten your code slightly you could use the
fetchAllKeyed()method of the database query to build that array of categories automatically. You don’t need thecategory_optionselement as you’ll already have access to that array in the$formvariable in your submission function.Also I’d be careful giving the outer and and inner elements the same name (
category), that might cause some problems.This code should help: