Providing suggester plugins

Last updated on
29 September 2017

Suggester plugins are the components responsible for actually creating the autocomplete suggestions that are displayed in reaction to user input. They use the normal Drupal 8 Plugin API, so defining new ones should be pretty simple for anyone familiar with it.

Key information

Plugin base class: \Drupal\search_api_autocomplete\Suggester\SuggesterPluginBase
Plugin namespace: Drupal\[MODULE]\Plugin\search_api_autocomplete\suggester
Annotation: @SearchApiAutocompleteSuggester
Service ID: plugin.manager.search_api_autocomplete.suggester

Important methods

The central method of a suggester plugin is the getAutocompleteSuggestions() method, which receives an (incomplete) search query and user input and should return an array of \Drupal\search_api_autocomplete\Suggestion\SuggestionInterface objects for the suggestions to display to the user. The method can either manually create \Drupal\search_api_autocomplete\Suggestion\Suggestion::__construct objects for the suggestions, or use the \Drupal\search_api_autocomplete\Suggestion\SuggestionFactory factory class that provides helper methods for creating the most common types of suggestions.
(As an alternative, you can of course also provide your own class implementing SuggestionInterface and create suggestions using that.)

Further available methods are supportsSearch() (for suggesters that don't support all searches, indexes or servers, or have some other requirements) and alterAutocompleteElement() (in case the suggester needs to add additional information on the form field to which autocomplete is added).

Finally, you can also implement \Drupal\Core\Plugin\PluginFormInterface in your suggester plugin class to provide a configuration form for users. In this case, you might want to use \Drupal\search_api\Plugin\PluginFormTrait to avoid some boilerplate code.
When the plugin can have configuration (even if no form is provided for it), defaultConfiguration() should also be implemented so that default settings can be applied correctly.

Help improve this page

Page status: No known problems

You can: