簡體   English   中英

選擇列表允許值

[英]select list allowed value

我有這段代碼可以在drupal中動態創建選擇列表。

$res = db_query("select field1 from content_type_1");
while($row = db_fetch_array($res)){
$rows[] =$row['field1'];
}
return $rows;

輸出就像:

<select>
<option value="0">row['field1']</option>
</select>

我需要這樣的輸出

<select>
<option value="row['field1']">row['field1']</option>
</select>

這個怎么做?

為了“符合drupal”,您的代碼應遵循編寫SQL查詢的“ drupal方式”。

您需要在SQL表的名稱周圍使用{...}(如果需要,這允許drupal添加前綴),並且您應該使用

$res = db_query("select field1 from {content_type_1}");
while ($row = db_fetch_array($res)) {
  $rows[] =$row['field1'];
}

然后,對於網站上的任何表單,都應使用表單APIselect語句)

因此,代碼應類似於:

function mymodule_form(&$form_state) {
  $form['mySelect'] = array(
   '#type' => 'select', 
   '#title' => t('A title'), 
   '#default_value' => '',
   '#options' => get_rows();
  );
  return $form
}

function get_rows() {
  $res = db_query("select field1 from {content_type_1}");
  while ($row = db_fetch_array($res)) {
    $rows[] = $row['field1'];
  }
return $rows; 
}

/* .. more code if needed .. */
// Then you can print your form.
// This should be called by a hook_menu or a theme() function ... not alone like here.
echo drupal_get_form('mySelect');

不確定,但我認為那是drupal:

  • 使用數組的鍵作為value屬性,
  • 並將數組的值用作<option>

如果是這種情況,將循環更改為此可以有所幫助:

while($row = db_fetch_array($res)){
    $rows[ $row['field1'] ] = $row['field1'];
}

現在,對於$rows數組的每個項目,鍵都與值相同。

現在可以確定,但是我從數據庫中選擇的大多數內容看起來像這樣的日志:

<select name="cctype">
    <option value="" selected = "Selected" >Pick one</option>
<?PHP
while($row = db_fetch_array($res)) {
    echo (' <option value="'.$row["field1"].'">'.$row["field1"].'</option>');
}
?>
</select>

希望能有所幫助。

銀虎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM