You are here

public static function MediaLibrary::valueCallback in Media Library Form API Element 8

Same name and namespace in other branches
  1. 2.x src/Element/MediaLibrary.php \Drupal\media_library_form_element\Element\MediaLibrary::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/MediaLibrary.php, line 323

Class

MediaLibrary
Provides a Media library form element.

Namespace

Drupal\media_library_form_element\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  $value = NULL;

  // Process the submission of our form element.
  if ($input !== FALSE && $input !== NULL && isset($input['media_library_selection'])) {
    $value = $input['media_library_selection'];
  }
  elseif ($input === FALSE) {
    if (!empty($element['#default_value'])) {

      // Remove the default value propery in case of AJAX removal.
      if ($form_state
        ->isSubmitted() && end($form_state
        ->getTriggeringElement()['#parents']) === 'remove_button') {
        $element['#default_value'] = NULL;
      }
      $value = $element['#default_value'];
    }
  }
  if (!empty($value)) {
    if (isset($value['target_id'])) {
      $value = $value['target_id'];
    }

    // Normalize 0 value.
    $value = $value === 0 ? '' : $value;
  }
  return $value;
}