2011-11-20 66 views
1

我使用下面的代碼將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'] 
); 

回答

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]; 
} 
+0

感謝。正是我在找什麼。 – Napoleon