function FormElement::processAutocomplete
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'
Parameters
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.
File
- 
              core/lib/ Drupal/ Core/ Render/ Element/ FormElement.php, line 176 
Class
- FormElement
- Provides a base class for form element plugins.
Namespace
Drupal\Core\Render\ElementCode
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'] : [];
    $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);
    }
    $metadata->merge(BubbleableMetadata::createFromObject($access))
      ->applyTo($element);
  }
  return $element;
}Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.
