我使用下面的代码将 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']
);
最佳答案
传递给提交函数中的 $form_state
数组的值将是 ID 而不是名称,它将是 drop 中选项的键下降,而不是值(value)。
如果您想稍微缩短代码,可以使用 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];
}
关于php - 如何使用查找表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202641/