/Drupal 8

public static function FormElement::processAutocomplete

public static FormElement::processAutocomplete(&$element, FormStateInterface $form_state, &$complete_form)

Adds autocomplete functionality to elements.

This sets up autocomplete functionality for elements with an #autocomplete_route_name property, using the #autocomplete_route_parameters property if present.

For example, suppose your autocomplete route name is 'mymodule.autocomplete' and its path is '/mymodule/autocomplete/{a}/{b}'. In a form array, you would create a text field with properties:

'#autocomplete_route_name' => 'mymodule.autocomplete',
'#autocomplete_route_parameters' => array('a' => $some_key, 'b' => $some_id),

If the user types "keywords" in that field, the full path called would be: 'mymodule_autocomplete/$some_key/$some_id?q=keywords'


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

  • #autocomplete_route_name: A route to be used as callback URL by the autocomplete JavaScript library.
  • #autocomplete_route_parameters: The parameters to be used in conjunction with the route name.

\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.


core/lib/Drupal/Core/Render/Element/FormElement.php, line 176


Provides a base class for form element plugins.




public static function processAutocomplete(&$element, FormStateInterface $form_state, &$complete_form) {
  $url = NULL;
  $access = FALSE;

  if (!empty($element['#autocomplete_route_name'])) {
    $parameters = isset($element['#autocomplete_route_parameters']) ? $element['#autocomplete_route_parameters'] : array();
    $url = Url::fromRoute($element['#autocomplete_route_name'], $parameters)->toString(TRUE);
    /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
    $access_manager = \Drupal::service('access_manager');
    $access = $access_manager->checkNamedRoute($element['#autocomplete_route_name'], $parameters, \Drupal::currentUser(), TRUE);

  if ($access) {
    $metadata = BubbleableMetadata::createFromRenderArray($element);
    if ($access->isAllowed()) {
      $element['#attributes']['class'][] = 'form-autocomplete';
      $metadata->addAttachments(['library' => ['core/drupal.autocomplete']]);
      // Provide a data attribute for the JavaScript behavior to bind to.
      $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl();
      $metadata = $metadata->merge($url);

  return $element;

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.