Drupal AJAX Framework with Multiple Instances of a Form
I recently encountered a unique issue with AJAX-ified form elements in Drupal. We’re building a site that shows the same form twice on a single page. I’m rendering both forms in two separate blocks; one appears at the top of the page, and one appears at the bottom.
The Select a Location field has an ajax callback to replace the the Select a Program select list with programs available at the chosen location. Initially, the top form worked as expected, but the bottom form would never get an updated Select a Program field. The AJAX callback seemed to run, but it would not replace the select list.
After fixing (by adding a unique, unchanging identifier, both forms performed as expected; changing the Select a Location dropdown updates the Select a Program dropdown, and the two forms do not interfere with one-another.
1 2 3 4 5 6 7 8 9 10 |
$form['field_rif_location'][LANGUAGE_NONE]['#ajax'] = array( 'callback' => 'mymodule_location_callback', - 'wrapper' => 'program-replace', + 'wrapper' => 'program-replace-' . $form['#build_id'], 'event' => 'change', ); - $form['field_rif_program'][LANGUAGE_NONE]['#prefix'] = '<div id="program-replace">'; + $form['field_rif_program'][LANGUAGE_NONE]['#prefix'] = "<div id='program-replace-{$form['#build_id']}'>"; $form['field_rif_program'][LANGUAGE_NONE]['#options'] = _mymodule_program_options($selected_location); |
Originally I tried using $form['#id'] because it looked cleaner, but it didn’t work correctly. The Select a Program list would update, but it’d have the same values every time, no matter which location was chosen.