How to create a custom Autocomplete using the Drupal 8 Form API
Tags: drupal, api, form
Published: 2020-06-26 07:02:49

In this article, I will **not explain** how to **customise/alter an Autocomplete Field Widget** - which should only be used on from using the Drupal Admin UI.

Here I will try to expose you a **step by step** guide which explains how you can create a custom Autocomplete field **using the Drupal 8 Form API Core feature** - An autocomplete that you could use in your own Drupal frontend applications.

![Example of custom Autocomplete using the Drupal 8 Form API](https://dev-to-uploads.s3.amazonaws.com/i/6dzuhaq1q7d4v3wa6f2q.gif)
<figcaption>This is what you will be able to achieve at the end of this story</figcaption>

If you are looking for resources which explains how to implement Views to alter an Autocomplete Field, please [refer to this excellent guide](https://www.drupal.org/docs/7/modules/entity-reference/using-a-view-to-display-the-elements-in-the-autocomplete-widget).

> Truth can only be found in one place: the code <br>
- Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

## Step 1- The autocomplete form element

The other day, I was asked to create a custom Autocomplete for a project which uses a custom Form build using the Drupal 8 Form API.

![](https://dev-to-uploads.s3.amazonaws.com/i/v8daaxjja6dcs51kf3dd.gif)

At first sight, you may be interested to use the `#entity_autocomplete` field type - it seems exactly what you need.
Unfortunately, this is not. Indeed, the `#entity_autocomplete` doesn't allow you any customisation.

So, you will need the old folk's `#textfield` and his cousin attribute `#autocomplete_route_name`

{% gist https://gist.github.com/WengerK/cb48d935df6a5be245e141b6610eb58a file=ArticleAutocompleteForm.php %}

The `#autocomplete_route_name` attribute will allow you to define a route to handle the autocomplete business logic (data you will return given the user input).

You also may add the `#autocomplete_route_parameters` attribute, this one gives you the possibility to send a fixed unalterable parameter to your `#autocomplete_route_name`, you may use it to fix the number of results to return.

## Step 2 - Define autocomplete route

Now you know how to create the autocomplete form, but you will need a route to manage the logic which will fetch data & return them.
How? By simply adding the reference to the route — where data will get retrieved from — to your _my_module.routing.yml_ file:

{% gist https://gist.github.com/WengerK/cb48d935df6a5be245e141b6610eb58a file=my_module.routing.yml %}

Be careful to use the same route name (here `my_module.autocomplete.articles`) in your previous `#autocomplete_route_name`.
Also, be sure to change permission according to your own needs.

## Step 3 - Add Controller and return JSON response

Now having a routing & a form, you have to define your custom controller, with the `handleAutocomplete` method.
Well, it's precisely this method that makes sure that the proper data gets collected and properly formatted once requested by Drupal.

Let's dig deeper and see how we can precisely deal with specific JSON response for our `textfield` element.

1. Setup an _ArticleAutoCompleteController_ class file under _my_module/src/Controller/ArticleAutoCompleteController.php_;
2. Then, extend the `ControllerBase` class and setup your handle method (in our case `::handleAutocomplete` see `my_module.routing.yml`).

{% gist https://gist.github.com/WengerK/cb48d935df6a5be245e141b6610eb58a file=ArticleAutoCompleteController.php %}

That's **pretty much all the hocus-pocus that you need** to have an autocomplete based on a textfield of Drupal 8.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1s3sdbuvt0bio5oz0dfb.gif)

<hr>
## Sources

For the most curious of you, here are some sources of additional information that inspired the creation of this article.

**Purushotam Rai** (24 November, 2016). Implementing #autocomplete in Drupal 8 with Custom Callbacks
See on [https://www.qed42.com/blog/autocom...](https://www.qed42.com/blog/autocomplete-drupal-8)

**Stijn Berkers** (28 February, 2018). How to produce a custom auto-complete field in drupal 8
See on [https://lucius.digital/en/blog/drupal...](https://www.lucius.digital/en/blog/drupal-module-conditional-redirect-released-on-drupal-org)

**Make-me-alive** (4 May, 2014). Adding autocomplete for text-field
See on [https://drupal.stackexchange.com/.../..](https://drupal.stackexchange.com/questions/200038/adding-autocomplete-for-text-field)

**Stijn Berkers** (18 July, 2018). How to add autocomplete to text fields in drupal 8: defining a custom route
See on [https://www.optasy.com/blog/how-add-autocom...](https://www.optasy.com/blog/how-add-autocomplete-text-fields-drupal-8-defining-custom-route)