You are here

public static function EntityAutocomplete::processEntityAutocomplete 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::processEntityAutocomplete()

Adds entity autocomplete functionality to a form element.

Parameters

array $element: The form element to process. Properties used:

  • #target_type: The ID of the target entity type.
  • #selection_handler: The plugin ID of the entity reference selection handler.
  • #selection_settings: An array of settings that will be passed to the selection handler.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

array $complete_form: The complete form structure.

Return value

array The form element.

Throws

\InvalidArgumentException Exception thrown when the #target_type or #autocreate['bundle'] are missing.

File

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

Class

EntityAutocomplete
Provides an entity autocomplete form element.

Namespace

Drupal\Core\Entity\Element

Code

public static function processEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {

  // Nothing to do if there is no target entity type.
  if (empty($element['#target_type'])) {
    throw new \InvalidArgumentException('Missing required #target_type parameter.');
  }

  // Provide default values and sanity checks for the #autocreate parameter.
  if ($element['#autocreate']) {
    if (!isset($element['#autocreate']['bundle'])) {
      throw new \InvalidArgumentException("Missing required #autocreate['bundle'] parameter.");
    }

    // Default the autocreate user ID to the current user.
    $element['#autocreate']['uid'] = isset($element['#autocreate']['uid']) ? $element['#autocreate']['uid'] : \Drupal::currentUser()
      ->id();
  }

  // Store the selection settings in the key/value store and pass a hashed key
  // in the route parameters.
  $selection_settings = isset($element['#selection_settings']) ? $element['#selection_settings'] : [];
  $data = serialize($selection_settings) . $element['#target_type'] . $element['#selection_handler'];
  $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());
  $key_value_storage = \Drupal::keyValue('entity_autocomplete');
  if (!$key_value_storage
    ->has($selection_settings_key)) {
    $key_value_storage
      ->set($selection_settings_key, $selection_settings);
  }
  $element['#autocomplete_route_name'] = 'system.entity_autocomplete';
  $element['#autocomplete_route_parameters'] = [
    'target_type' => $element['#target_type'],
    'selection_handler' => $element['#selection_handler'],
    'selection_settings_key' => $selection_settings_key,
  ];
  return $element;
}