Autocomplete function for textfield of Form API | Drupal 8

Autocomplete function for textfield of Form API

Submitted by editor on Tue, 09/12/2017 - 15:10

How to create an autocomplete text field using drupal 8 Form API ?

First, Create autocomplete controller and the route

Example of the controller : DefaultController.php


namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Controller\ControllerBase;

class DefaultController extends ControllerBase{
   * Returns response for the autocompletion.
  public function autocomplete(Request $request) {
    $matches = ['Value 1', 'Value 2', '... ...'];
    return new JsonResponse($matches);

Example of the route : mymodule.routing.yml

  path: '/mymodule/autocomplete'
    _controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
    _access: 'TRUE'

Then add this route to the field

Example :

$form['myfield'] = [
  '#type' => 'textfield',
  '#title' => t('Autocomplete text field'),
  '#autocomplete_route_name' => 'mymodule.autocomplete',

See Entity Autocomplete From here


maya (not verified)

Tue, 01/23/2018 - 11:01


j'ai un array de  70326 valeurs,la recherche ne parche pas.

Pouvez vouz me conseiller 


youssouf (not verified)

Fri, 06/08/2018 - 11:04

How to retrieve data from solr index or database using your issue ?

Do you know how to simply add autocomplete search api on custom form programmatically !

thank you in advance !

Sandip T (not verified)

Tue, 02/25/2020 - 15:04

All the posts I've combed through, I get examples of 'autocomplete' added to the newly creating form elements. Can I not alter the existing form (e.g. content type node add form) and add the autotcomplete to one of it's field ? I tried with given above example for D 8.8 and instead of adding route to the new field, I added to existing field in edit. Failed and Failed and tons of time it just failed... Any suggestion ?

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.