You are here

public static function YamlFormOtherBase::valueCallback in YAML Form 8

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/YamlFormOtherBase.php, line 135

Class

YamlFormOtherBase
Base class for form other element.

Namespace

Drupal\yamlform\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

  // Remove 'yamlform_' prefix from type.
  $type = str_replace('yamlform_', '', static::$type);
  if ($input === FALSE) {
    $default_value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
    if (!$default_value) {
      return $element;
    }
    if (static::isMultiple($element)) {
      if (is_array($default_value)) {
        $flattened_options = OptGroup::flattenOptions($element['#options']);
        if ($other_options = array_diff_key(array_combine($default_value, $default_value), $flattened_options)) {
          $element[$type]['#default_value'] = $default_value + [
            static::OTHER_OPTION => static::OTHER_OPTION,
          ];
          $element['other']['#default_value'] = implode($element['#other__option_delimiter'], $other_options);
        }
        return $element;
      }
    }
    elseif (!YamlFormOptionsHelper::hasOption($default_value, $element['#options'])) {
      $element[$type]['#default_value'] = static::OTHER_OPTION;
      $element['other']['#default_value'] = $default_value;
      return $element;
    }
    else {
      return $element;
    }
  }
  return NULL;
}