Fix for AHAH FAPI Callback Helper

  1. // Example usage. This is an AHAH callback function.
  2. function mymodule_ahah() {
  3.   // Update the form and render only the wrapper inside the "Refund Settings"
  4.   // fieldset.
  5.   $form_update_callbacks['some_fieldset][important_data_wrapper'] = array(
  6.     'callback'           => '_mymodule_form_important_data',
  7.     'callback arguments' => array($_POST['some_setting'], $_POST['another_setting'], 'and another one'),
  8.   );
  9.   // Possibly more entries for $form_update_callbacks here.
  10.   $form_element_to_render = 'some_fieldset][important_data_wrapper';
  11.   ahah_helper_render($form_update_callbacks, $form_element_to_render);
  12. }
  13.  
  14.  
  15.  
  16.  
  17. /**
  18.  * This will become ahah_helper.module?!
  19.  */
  20. function ahah_helper_render($form_update_callbacks = array(), $form_element_to_render) {
  21.   $form_state = array('submitted' => FALSE);
  22.   $form_build_id = $_POST['form_build_id'];
  23.  
  24.   // Add the new element to the stored form. Without adding the element to the
  25.   // form, Drupal is not aware of this new elements existence and will not
  26.   // process it. We retrieve the cached form, add the element, and resave.
  27.   $form = form_get_cache($form_build_id, $form_state);
  28.   foreach ($form_update_callbacks as $form_element_name => $settings) {
  29.     $form_element =& ahah_helper_get_form_element($form, $form_element_name);
  30.     $form_element = call_user_func_array($settings['callback'], $settings['callback arguments']);
  31.   }
  32.   form_set_cache($form_build_id, $form, $form_state);
  33.  
  34.   // Rebuild the form.
  35.   $form += array(
  36.     '#post'       => $_POST,
  37.     '#programmed' => FALSE,
  38.   );
  39.   $form = form_builder($_POST['form_id'], $form, $form_state);
  40.  
  41.   drupal_json(array(
  42.     'status' => TRUE,
  43.     'data'   => drupal_render(ahah_helper_get_form_element($form, $form_element_to_render)),
  44.   ));
  45. }
  46.  
  47.  
  48. function &ahah_helper_get_form_element(&$form, $parents) {
  49.   // Allow $parents to be either an array of the element's parents or the name
  50.   // of an element.
  51.   if (strpos($parents, ']') !== FALSE) {
  52.     $parents = explode('][', $parents);
  53.   }
  54.  
  55.   // Recursively seek the form element.
  56.   if (count($parents)) {
  57.     $parent = array_shift($parents);
  58.     return ahah_helper_get_form_element(&$form[$parent], $parents);
  59.   }
  60.   else {
  61.     return $form;
  62.   }
  63. }

Submit Fix

Any tags you'd like to associate with your code, delimitered by commas (example: Views, CCK, Module, etc).
Select the syntax highlighting mode to use.