Reputation: 2214
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
Upvotes: 2
Views: 105
Reputation: 19441
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')
.
Upvotes: 4