views:

46

answers:

1

Hello

I'm trying to teach myself Drupal and I've found something I can't find any tutorials for.

I am trying to generate a form, with a dynamic number of text fields, to populate and edit the contents of my custom table. In regular PHP I would achieve this with:

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

Can someone point me to something that'll show me how to do that in Drupal (and processing the submited data)?

Thanks

+4  A: 

Check the forms API reference and the Form API Quickstart Guide for this.

A simple version of your example would look something like the following:

/**
 * 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
  }
}

(NOTE: Untested code, beware of typos and other errors)

To prepare the form for output, you'd call drupal_get_form('yourModule_table_edit_form').

Henrik Opel
Drupal has a database API too; instead of using functions that are specific for a database, Drupal code should use the database abstraction API, and use `db_query()`, `db_query_range()`, `db_fetch_array()`, `db_fetch_object()`, etc.
kiamlaluno
@kiamlaluno: Good point - I adjusted the example accordingly.
Henrik Opel
Sorry for the delayed response. It looks right for what I'm trying, so I'll try it once I have the table install/uninstall working.
YsoL8
If you're still watching, I'm starting to implement this
YsoL8