从数据库生成表单

时间:2010-06-16 10:43:20

标签: php drupal drupal-6

我正在努力教自己Drupal,我发现了一些我找不到任何教程的东西。

我正在尝试使用动态数量的文本字段生成表单,以填充和编辑自定义表的内容。在常规PHP中,我将通过以下方式实现此目的:

$count = '0';
while ($row = mysql_fetch_array ($result) {
  echo "<input type='text' name='title_row".$count."' value='".$row['title']."'>"
  $count = $count +1;
}

有人能指出我会告诉我如何在Drupal中执行此操作(并处理提交的数据)吗?

谢谢

1 个答案:

答案 0 :(得分:4)

检查forms API referenceForm API Quickstart Guide

您示例的简单版本如下所示:

/**
 * Form builder function - creates definition of form
 */
function yourModule_table_edit_form($form_state) {
  $form = array();
  // TODO: Add code/query to populate $result, using the 
  // Drupal DAL functions, e.g.:
  $result = db_query('SELECT * FROM {your_table}');
  while ($row = db_fetch_array($result) {
    // Create one textfield per row
    // NOTE: assumes content of title column can be used as an array index
    $form[$row['title']] = array(
      '#type' => 'textfield',
      '#title' => $row['title'],
      '#default_value' => $row['value'], // NOTE: Just assumed the column name
      '#size' => 60, // Adjust as needed
      '#maxlength' => 60, // Adjust as needed
      // NOTE: more options for input element definition available - check the API docs
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

/**
 * Form submit function
 */
function yourModule_table_edit_form_submit($form, &$form_state) {
  foreach ($form_state['values'] as $row_title => $value) {
    // TODO: Do something with the submitted values
  }
}

(注意:未经测试的代码,谨防拼写错误和其他错误)

要准备输出表单,请拨打drupal_get_form('yourModule_table_edit_form')