Drupal 6 - Multiple instances of the same form on one page
Steven Jones
There's an excellent article over on gtrlabs: Drupal 5: How to process multiple instances of the same form on the same page that describes in detail how to have multiple copies of the same form on the same page. There are some subtle differences to use this technique in Drupal 6, which I'll explain below.
The idea of this technique is simple, drupal forms are identified by their 'form_id' and these ids must be unique on a page, so if you want the same form to appear more than once, you need to change the 'form_id' somehow. We do this by appending a number to our 'form_id':
function example_view($things = array()) {
for ($i=0; $i < count($things); $i++) {
$output = drupal_get_form("example_thing_form_" . $i, $things[$i]);
}
return $output;
}
Now drupal will look for form building functions: example_thing_form_1
, example_thing_form_2
, etc. But we don't want to create lots and lots of these functions manually, so we intercept the form building process using hook_forms()
this hook gets called by drupal_retrieve_form()
if drupal can't find a specific form building function. The first argument passed is the 'form_id' and we can return a function to build the form thus:
function example_forms($form_id) {
$forms = array();
if (strpos($form_id, 'example_thing_form_') === 0) {
$forms[$form_id] = array(
'callback' => 'example_thing_form',
);
}
return $forms;
}
Now we just need to build the form as normal in our example_thing_form
function albeit with one caveat, the default validation and submission handlers that would be called are example_thing_form_1_submit
, so to have common submit handlers we need to specify them in our form building function thus:
function example_thing_form($form_state, $thing) {
$form = array();
$form['#submit'] = array(
'example_thing_form_submit',
);
// Add other bits of form definition here:
return $form;
}
I used this technique to render the output of a views handler as a form, it made it very easy to add a select box to a table, without needing to write a style plugin.
Happy coding.