I need to add a auto complete text field in my custom form module. The auto complete values should be retrieved from the database table. Can anybody tell me how to do that?


To add an autocomplete to a form element that is not an entity reference element, you need to use two properties:

  • #autocomplete_route_name, the name of the route returning the autocomplete array as JSON
  • (optional) #autocomplete_route_parameters, an array of parameters to pass to the autocomplete route, in the format [<parameter> => <value>]

For example, the autocomplete controller could be implemented from a class similar to the following one.

 * Defines a route controller for autocomplete form elements.
class AutocompleteController extends ControllerBase {

   * Handler for the autocomplete request.
  public function autocomplete(Request $request) {
    $results = [];

    // Get the typed string from the URL, if it exists.
    if ($input = $request->query->get('q')) {
      $typed_string = Tags::explode($input);
      $typed_string = Unicode::strtolower(array_pop($typed_string));

      // Use $typed_string to load data from the database.

      $results[] = [
        'value' => $value,
        'label' => $label,

    return new JsonResponse($results);


Notice that:

  • The value entered in the form element is available in $request->query->get('q')
  • The autocomplete returns an array containing entries with value (the value to use) and label (the value to show), converted in JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.