Mr Treublaan 1-3
1097 DP Amsterdam
The Netherlands

How to produce a custom auto-complete field in Drupal 8

28 Feb, 2018 Drupal

Home Blog How to produce a custom a...

drupal custom auto complete field

Currently we are busy building a realtime chat platform called Lus. In Lus we connected Drupal to NodeJS for a blazing fast system, with realtime communication (chats, tasks & file sharing).

Within Lus, people can cooperate in ‘channels’, comparable to the WhatsApp groups. Team communication takes place in these channels. A channels works best if you organize it around a certain topic, like ‘sales’.

As soon as a new channel is being started, existing team members can be added in the easiest way imaginable: with the help of a ‘auto-complete field’: as soon as you start typing, suggestions will immediately pop up, in this case for names of team members:

This auto-complete field has been custom developed by us, in part because our Drupal installation uses custom database charts which aren’t available in Drupal 8 core. How did we do it:

1. The form element

To get started we need the Drupal auto complete form element, allowing users on the front end to pick the desired team members. We define this as follows:

Because we use #autocomplete_route_name element, Drupal knows that such a form element has to be ignored on the front end.

2. Custom route

As you can see in the form element, a reference is made to the route, from which data has to be obtained. We’ll add these in the .routing.yml file:

This routing.yml file is already in our module’s root.

3. Controller with custom query

In the route we just created we refer to a custom controller AutocompleteController, method handleAutocomplete. This one can be found in the map moduleroot/src/Controller:

This method ensures that the right data is collected from the data base and will be given back correctly formatted as well.

Wrap it up

As you can see, suggestions are being given for code corrections. In an optimization run we’ll get onto it. For now, at least the data is coming though correctly and we can create new channels with existing team members by means of a auto-complete field.

Credits header foto: ricardo Gomez Angel

Written by Joris Snoek | Feb 28, 2018
Let's Talk

Please tell me all about your project!
Mail , or send a message:

Got some more time?

Related content
09 May, 2023 Drupal

Save time, frustration, and potential content loss.


07 Jun, 2021 Drupal

Programmatically in multiple Views


02 Jun, 2021 Drupal