Rendering the same for twice leads to incorrect submission

If you render the same form (with the same exact form id) on the same page more than once, Drupal will incorrectly submit all matching forms on the page to the first-rendered form. To avoid this, you must create dynamic form ids. This can be achieved by using hook_forms() to map dynamic form ids to the appropriate callbacks.

Here's an example from the usasearch_field module:

<?php
$form_id
= 'usasearch_field_search_box_' . $id . '_' . $field_name . '_' . $delta;
$form = drupal_get_form($form_id, NULL, NULL, NULL, NULL, 'usasearch_field', $item['usasearch_field_affiliate']);
?>

This dynamic form id is handled by usasearch_field_forms():

<?php
/**
* Implements hook_forms().
*/
function usasearch_field_forms($form_id, $args) {
 
$forms = array();

  if (strpos($form_id, 'usasearch_field_search_box_') !== FALSE) {
   
$forms[$form_id] = array(
     
'callback' => 'search_box',
     
'callback arguments' => array('search_block_form'),
    );
  }

  return $forms;
}
?>

This form can then be modified by searching for a matching form_id in an alter hook:

<?php
/**
* Implements hook_form_alter().
*
* Changes elements in the search block, search theme form, search page form.
*/
function usasearch_field_form_alter(&$form, &$form_state, $form_id) {
 
// Search block and search box have similar form structure.
 
if (strpos($form_id, 'usasearch_field_search_box_') !== FALSE) {
     
$form['#submit'][] = 'usasearch_field_form_submit';
  }
}
?>
Drupal Version Compatibility: 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.