You are here

function conditional_fields_dependent_validate in Conditional Fields 7.3

Dependent field validation callback.

If the dependencies of a dependent field are not triggered, the validation errors that it might have thrown must be removed, together with its submitted values. This will simulate the field not being present in the form at all. In this field-level callback we just collect needed information and store it in $form_state. Values and errors will be removed in a single sweep in conditional_fields_form_validate(), which runs at the end of the validation cycle.

See also

conditional_fields_form_validate()

1 string reference to 'conditional_fields_dependent_validate'
conditional_fields_form_after_build in ./conditional_fields.module
after_build callback for forms with dependencies.

File

./conditional_fields.module, line 674
Define dependencies between fields based on their states and values.

Code

function conditional_fields_dependent_validate($element, &$form_state, $form) {
  $dependent = $element[$element['#language']];

  // Check if this field's dependencies were triggered.
  if (conditional_fields_evaluate_dependencies($dependent, $form, $form_state)) {
    return;
  }

  // Mark submitted values for removal. We have to remove them after all fields
  // have been validated to avoid collision between dependencies.
  $form_state_addition['parents'] = $dependent['#array_parents'];

  // Optional behavior: reset the field to its default values.
  // Default values are always valid, so it's safe to skip validation.
  if (!empty($element['#conditional_fields_reset_if_untriggered'])) {
    $form_state_addition['reset'] = TRUE;
  }

  // Tag validation errors previously set on this field for removal in
  // conditional_fields_form_validate().
  $errors = form_get_errors();
  if ($errors) {
    $error_key = implode('][', $dependent['#parents']);
    foreach ($errors as $name => $error) {

      // An error triggered by this field might have been set on a descendant
      // element. This also means that so there can be multiple errors on the
      // same field (even though Drupal doesn't support multiple errors on the
      // same element).
      if (strpos($name, $error_key) === 0) {
        $field_errors[$name] = $error;
      }
    }
  }
  if (!empty($field_errors)) {
    $form_state_addition['errors'] = $field_errors;
  }
  $form_state['conditional_fields_untriggered_dependents'][] = $form_state_addition;
}