我使用下面的代码将am_category表中的所有类别放入表单中的下拉框中。有用。但是在提交表单时我需要category.ID而不是名称。如何通常使用像这样的查找表?
$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']
);
答案 0 :(得分:2)
传递给提交函数中$form_state
数组的值将是ID而不是名称,它将是下拉列表中选项的关键,而不是值。
如果您想稍微缩短代码,可以使用数据库查询的fetchAllKeyed()
方法自动构建该类别数组。您不需要category_options
元素,因为您已经可以在提交函数的$form
变量中访问该数组。
另外,我要小心赋予外部和内部元素相同的名称(category
),这可能会导致一些问题。
此代码应该有所帮助:
function mymodule_myform($form, &$form_state) {
$categories = db_query("SELECT id, name FROM {am_category}")->fetchAllKeyed();
$form['category_wrapper']['category'] = array(
'#type' => 'select',
'#title' => t('Category'),
'#description' => t('Please select the category of this achievement.'),
'#options' => $categories
);
return $form;
}
function mymodule_myform_submit(&$form, &$form_state) {
$selected_category_id = $form_state['values']['category'];
// Just in case you wanted to know, this would get the corresponding name for the selected category:
$selected_category_name = $form['category_wrapper']['category']['#options'][$selected_category_id];
}