You are here

public static function EntityAutocomplete::valueCallback in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php \Drupal\Core\Entity\Element\EntityAutocomplete::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 Textfield::valueCallback

File

core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php, line 100

Class

EntityAutocomplete
Provides an entity autocomplete form element.

Namespace

Drupal\Core\Entity\Element

Code

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

  // Process the #default_value property.
  if ($input === FALSE && isset($element['#default_value']) && $element['#process_default_value']) {
    if (is_array($element['#default_value']) && $element['#tags'] !== TRUE) {
      throw new \InvalidArgumentException('The #default_value property is an array but the form element does not allow multiple values.');
    }
    elseif (!empty($element['#default_value']) && !is_array($element['#default_value'])) {

      // Convert the default value into an array for easier processing in
      // static::getEntityLabels().
      $element['#default_value'] = [
        $element['#default_value'],
      ];
    }
    if ($element['#default_value']) {
      if (!reset($element['#default_value']) instanceof EntityInterface) {
        throw new \InvalidArgumentException('The #default_value property has to be an entity object or an array of entity objects.');
      }

      // Extract the labels from the passed-in entity objects, taking access
      // checks into account.
      return static::getEntityLabels($element['#default_value']);
    }
  }

  // Potentially the #value is set directly, so it contains the 'target_id'
  // array structure instead of a string.
  if ($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);
    return static::getEntityLabels($entities);
  }
}