php - 如何使用查找表?

标签 php mysql drupal drupal-7

我使用下面的代码将 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/

相关文章:

php - 使用 nginx 的 wordpress 空白页面

php - 使用 PDO 进行错误处理的最佳实践

java - 如何将ArrayList插入数据库

sql - MySQL:在 CREATE TABLE 语句中命名主键

html - 为什么我不能在输入字段中选择和输入数据?

php - Drupal模板if语句

PHP,检查 My-Sql 数据中的值

php - 查找值所在的表名? MySQL PHP

mysql - 如何使用 CURL 将 .csv 文件从本地计算机 (Getfile) 发送到 Apache Nifi 中的 Hive(Puthiveql)?

Drupal 7 : Template for user registration page?