You are here

function subform_init in Subform 7

Implements hook_init().

If the current request is a ajax form submission and contains the special input key '_subform_element_name', the ajax path or callback expects the form structure and state of the subform. If this is the case rewrite $_POST and $_FILES so they contain the subform specific data only.

During a ajax form submission only functions starting with "subform_form_" are called; all "subform_element_" and all "subform_parent_" functions are irrelevant.

Contains the code that renames input elements inside subforms and allows for ajax form submissions. Functions that get called during a ajax form submission.

See also

subform_form_child_pre_render()

subform_form_process()

subform_form_after_build()

File

./subform.module, line 82
Defines a subform element type.

Code

function subform_init() {
  if (isset($_POST['_subform_element_name'])) {
    $subform_name = $_POST['_subform_element_name'];
    $wrapper_input = $_POST;
    $_POST = isset($_POST[$subform_name]) ? $_POST[$subform_name] : array();
    if (!empty($wrapper_input)) {
      foreach ($wrapper_input as $name => $value) {
        if (strpos($name, $subform_name . '-') === 0) {
          $_POST[$name] = $value;
        }
      }
    }

    //$_POST['_subform_wrapper_input'] = $wrapper_input;

    // This is hacky, but it works: _subform_element_name is supposed to
    // be the first non-form-input value.
    $non_form_input = FALSE;
    foreach ($wrapper_input as $key => $value) {
      if ($key == '_subform_element_name') {
        $non_form_input = TRUE;
      }
      elseif ($non_form_input) {
        $_POST[$key] = $value;
      }
    }
    if (!empty($_FILES['files'])) {
      foreach ($_FILES['files']['name'] as $old_name => $value) {
        if (strpos($old_name, $subform_name . '-') === 0) {

          // Remove the subform element name prefix.
          $new_name = substr($old_name, strlen($subform_name . '-'));
          foreach (array(
            'name',
            'type',
            'tmp_name',
            'error',
            'size',
          ) as $key) {
            $_FILES['files'][$key][$new_name] = $_FILES['files'][$key][$old_name];
            unset($_FILES['files'][$key][$old_name]);
          }
        }
      }
    }
  }
}