You are here

public function CustomScript::alterAutocompleteElement in Search API Autocomplete 8

Alters an autocomplete element that should use this suggester.

This method is usually not needed by suggester plugins, but can be implemented when necessary to, for example, pass additional information to the autocomplete AJAX callback.

Parameters

array $element: The render array of the autocomplete element.

Overrides SuggesterPluginBase::alterAutocompleteElement

File

src/Plugin/search_api_autocomplete/suggester/CustomScript.php, line 74

Class

CustomScript
Uses a custom (non-Drupal) script for generating autocomplete suggestions.

Namespace

Drupal\search_api_autocomplete\Plugin\search_api_autocomplete\suggester

Code

public function alterAutocompleteElement(array &$element) {
  $options['query'] = $element['#autocomplete_route_parameters'];
  unset($element['#autocomplete_route_name'], $element['#autocomplete_route_parameters']);
  $path = $this->configuration['path'];
  $path_len = strlen($path);

  // We allow both internal and external URLs to be used.
  if ($path_len > 1 && $path[0] === '/' && ($path_len < 2 || $path[1] !== '/')) {
    $url = Url::fromUserInput($path, $options);
  }
  else {
    $url = Url::fromUri($path, $options);
  }
  $url = $url
    ->toString(TRUE);

  // Without the "#autocomplete_route_name", we need to inline
  // \Drupal\Core\Render\Element\FormElement::processAutocomplete().
  $element['#attributes']['class'][] = 'form-autocomplete';

  // Provide a data attribute for the JavaScript behavior to bind to.
  $element['#attributes']['data-autocomplete-path'] = $url
    ->getGeneratedUrl();
  $metadata = BubbleableMetadata::createFromRenderArray($element);
  $metadata
    ->merge($url)
    ->applyTo($element);
}