You are here

public static function MultiValue::valueCallback in SAML Authentication 4.x

Same name and namespace in other branches
  1. 8.3 src/Element/MultiValue.php \Drupal\samlauth\Element\MultiValue::valueCallback()

Determines how user input is mapped to an element's #value property.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

mixed The value to assign to the element.

Overrides FormElement::valueCallback

File

src/Element/MultiValue.php, line 322

Class

MultiValue
Provides a multi-value form element.

Namespace

Drupal\samlauth\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  if ($input !== FALSE) {
    return $input;
  }
  $value = [];
  $element += [
    '#default_value' => [],
  ];
  $children_keys = Element::children($element, FALSE);
  $first_child = reset($children_keys);
  $children_count = count($children_keys);
  foreach ($element['#default_value'] as $delta => $default_value) {

    // Enforce numeric deltas.
    if (!is_numeric($delta)) {
      continue;
    }

    // Allow to omit the child element name when one single child exists and
    // the values are simple literals. This allows to pass
    // [0 => 'value 1', 1 => 'value 2'] instead of
    // [0 => ['element_name' => 'value 1', 1 => ['element_name' => ...]].
    if ($children_count === 1 && !is_array($default_value)) {
      $value[$delta] = [
        $first_child => $default_value,
      ];
    }
    else {
      $value[$delta] = $default_value;
    }
  }
  return $value;
}