Drupal表单选项从循环填充

时间:2012-01-19 10:27:53

标签: forms drupal drupal-7 drupal-forms

我想从循环

填充select选项
$form['vote']['selected'] = array(
 '#type' => 'select',
 '#title' => 'Select',
 '#name' => 'name',
 ); 

 foreach($loop as $row)
 $form['vote']['selected']['#options'] = array($row->id => $row->name);
 }

 return $form;

需要一些帮助?

1 个答案:

答案 0 :(得分:2)

这是执行此操作的标准方法:

$options = array();
foreach($loop as $row)
  $options[$row->id] = $row->name;
}

$form['vote']['selected'] = array(
  '#type' => 'select',
  '#title' => 'Select',
  '#name' => 'name',
  '#options' => $options
); 

您还可以查看数据库查询的fetchAllKeyed方法,这是将数据库中的数据转换为适合选择列表的键控数组的便捷快捷方式:

$options = db_query('SELECT id, name FROM {table}')->fetchAllKeyed();

以上内容与上面的foreach循环完全相同。