2011-12-15 48 views
0

我還在我自己的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; 
} 

回答

3

你只是忘記了#options鍵添加到您的選擇元素的代碼,代碼應該這樣寫:

$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的組合,稍微縮短您的查詢/選項代碼:

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

該死的我是那麼不小心,就在我以爲我已經檢查過了。謝謝克萊夫 – Altic

相關問題