Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Autocomplete function for textfield of Form API

By editor , 12 September, 2017
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

Tags

  • Drupal 8
  • Code
  • Form
  • Add new comment
Create a Form with Drupal 8 using Form API

Comments2

Plain text

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

maya (not verified)

8 years 10 months ago

bonjour,…

bonjour,

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

Pouvez vouz me conseiller 

merci

  • Reply

youssouf (not verified)

8 years 5 months ago

retrieve data

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 !

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer