1.20.x layout.admin.inc layout_ajax_form_update($form, $form_state)

AJAX handler that updates a portion of the form.

This is meant for generic use. It depends on a few variables in $form_state:

  • $form_state['ajax_rebuild_form']: The function name that builds the form that will be updated.
  • $form_state['ajax_update']: An array of keys representing the portion of the form that should be updated.

File

modules/layout/layout.admin.inc, line 2844
Admin page callbacks for the Layout module.

Code

function layout_ajax_form_update($form, $form_state) {
  if (!isset($form_state['ajax_update'])) {
    return NULL;
  }

  // If updating an entirely different form, build the form and pull out the new
  // pieces.
  if (isset($form_state['ajax_rebuild_form'])) {
    $form_state += array(
      'ajax_rebuild_args' => array(),
    );
    $args = array_merge(array($form_state['ajax_rebuild_form']), $form_state['ajax_rebuild_args']);
    $replace_form = call_user_func_array('backdrop_get_form', $args);
  }
  // Or if just rebuilding the current form, rebuild it directly.
  else {
    $replace_form = backdrop_rebuild_form($form['#form_id'], $form_state, $form);
  }

  // Remove any ID incrementation that could happen on the form ID.
  $form_id = preg_replace('/--\d$/', '', $replace_form['#id']);
  $build_id = backdrop_render($replace_form['form_build_id']);

  // Narrow down the form to just the part that will be replaced.
  $replace_portion = $form_state['ajax_update'];
  foreach ($replace_portion as $parent) {
    if (isset($replace_form[$parent])) {
      $replace_form = $replace_form[$parent];
    }
    else {
      $replace_form = FALSE;
      break;
    }
  }

  $commands = array();
  if ($replace_form) {
    // Update the portion of the form.
    $html = backdrop_render($replace_form);
    $commands[] = ajax_command_replace('#' . $replace_form['#id'], $html);
    // And update the build ID so these new values are included when saving.
    $commands[] = ajax_command_replace('#' . $form_id . ' input[name="form_build_id"]', $build_id);
  }
  else {
    // @todo: Provide an error message if the target is not found.
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}