如何将数据库内容加载到下拉选项(选择)

时间:2011-12-15 11:27:15

标签: drupal drupal-7 drupal-modules

我仍在使用我自己的drupal 7模块,我遇到了一些麻烦。我正在尝试将数据库内容加载到下拉选项(选择),我已经从drupal示例读取和编写相同的代码,但我的数据库仍然没有加载,只有空选项。 我问的是我的代码有什么问题,或者除了drupal示例之外还有更快的方法将数据库加载到下拉选项???

这里是我正在处理的代码

function prod_entry_load($entry = array()) {
  $select = db_select('aa_1122','aa');
  $select->fields('aa');

  foreach ($entry as $field => $value) {
    $select->condition($field, $value);
  }
  return $select->execute()->fetchAll();
}

function prod(){
    return drupal_get_form('prod_form');
}
function prod_form($form_state){
  $form = array(
      '#prefix' => '<div id="updateform">',
      '#suffix' => '</div>',
  );

  $entries = prod_entry_load();
  $keyed_entries = array();
  if (empty($entries)) {
    $form['no_values'] = array(
      '#value' => t("No entries exist in the table dbtng_example table."),
    );
    return $form;
  }

  foreach ($entries as $entry) {
    $options[$entry->no] = t("@no: @name ", array('@no' => $entry->no, '@name' => $entry->name));
    $keyed_entries[$entry->no] = $entry;
  }
  $default_entry = !empty($form_state['values']['no']) ? $keyed_entries[$form_state['values']['no']] : $entries[0];

  $form_state['entries'] = $keyed_entries;

  $form['no'] = array(
    '#type' => 'select',
    '#title' => t('Choose'),
    '#default_value' => $default_entry->no,
    '#ajax' => array(
        'wrapper' => 'updateform',
        'callback' => 'prod_form_update_callback',
    ),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#ajax' => array(
      'callback' => 'ajax_alert',
    ),
  );
  return $form;
}

function prod_form_update_callback($form, $form_state) {
  $entry = $form_state['entries'][$form_state['values']['no']];  
  foreach (array('name') as $item) {
    $form[$item]['#value'] = $entry->$item;
  }
  return $form;
}

1 个答案:

答案 0 :(得分:3)

您忘记将#options键添加到select元素中,代码应如下所示:

$form['no'] = array(
  '#type' => 'select',
  '#title' => t('Choose'),
  '#default_value' => $default_entry->no,
  '#options' => $options, // This is the bit that was missing
  '#ajax' => array(
    'wrapper' => 'updateform',
    'callback' => 'prod_form_update_callback',
  ),
);

您可以使用MySQL中的字符串连接和db fetchAllKeyed()方法稍微缩短查询/选项代码:

$query = db_select('aa_1122', 'aa')->fields('aa', array('no'));
$query->addExpression("CONCAT(no, ': ', name)", 'display');
$options = $query->execute()->fetchAllKeyed();