function EntityAutocomplete::valueCallback

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php \Drupal\Core\Entity\Element\EntityAutocomplete::valueCallback()
  2. 10 core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php \Drupal\Core\Entity\Element\EntityAutocomplete::valueCallback()
  3. 11.x core/lib/Drupal/Core/Entity/Element/EntityAutocomplete.php \Drupal\Core\Entity\Element\EntityAutocomplete::valueCallback()

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);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.