You are here

public static function SynonymsEntityAutocomplete::valueCallback in Synonyms 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 Textfield::valueCallback

File

src/Element/SynonymsEntityAutocomplete.php, line 55

Class

SynonymsEntityAutocomplete
Form element for synonyms-friendly entity autocomplete.

Namespace

Drupal\synonyms\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  $entities = NULL;
  if ($input === FALSE) {
    if (isset($element['#default_value'])) {
      $entities = [];
      foreach ($element['#default_value'] as $entity) {
        $entities[] = $entity;
      }
    }
  }
  elseif ($input !== FALSE && is_array($input)) {
    $entity_ids = array_map(function (array $item) {
      return $item['target_id'];
    }, $input);
    $entities = \Drupal::entityTypeManager()
      ->getStorage($element['#target_type'])
      ->loadMultiple($entity_ids);
  }
  if (is_array($entities)) {
    $value = [];
    foreach ($entities as $entity) {
      $value[] = $entity
        ->label() . ' (' . $entity
        ->id() . ')';
    }
    return Tags::implode($value);
  }
}