You are here

public static function ElementBase::valueCallback in Select (or other) 8.3

Same name and namespace in other branches
  1. 8 src/Element/ElementBase.php \Drupal\select_or_other\Element\ElementBase::valueCallback()
  2. 4.x src/Element/ElementBase.php \Drupal\select_or_other\Element\ElementBase::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

1 call to ElementBase::valueCallback()
ElementsTest::testValueCallback in Tests/src/Unit/ElementsTest.php
Tests the value callback.

File

src/Element/ElementBase.php, line 100
Contains Drupal\select_or_other\Element\ElementBase.

Class

ElementBase
Base class for select or other form elements.

Namespace

Drupal\select_or_other\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  $values = [];
  if ($input !== FALSE && !empty($input['select'])) {
    if ($element['#multiple']) {
      $values = [
        'select' => (array) $input['select'],
        'other' => !empty($input['other']) ? (array) $input['other'] : [],
      ];
      if (in_array('select_or_other', $values['select'])) {
        $values['select'] = array_diff($values['select'], [
          'select_or_other',
        ]);
      }
      else {
        $values['other'] = [];
      }
      if (isset($element['#merged_values']) && $element['#merged_values']) {
        if (!empty($values['other'])) {
          $values = array_merge($values['select'], $values['other']);

          // Add the other option to the available options to prevent
          // validation errors.
          $element['#options'][$input['other']] = $input['other'];
        }
        else {
          $values = $values['select'];
        }
      }
    }
    else {
      if ($input['select'] === 'select_or_other') {
        $values = [
          $input['other'],
        ];

        // Add the other option to the available options to prevent
        // validation errors.
        $element['#options'][$input['other']] = $input['other'];
      }
      else {
        $values = [
          $input['select'],
        ];
      }
    }
  }
  return $values;
}