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
Question

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

<?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

mymodule.autocomplete:
  path: '/mymodule/autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
  requirements:
    _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

Add new comment