I am struggeling with creation of tetxfield with autocomplete option for my Drupal 8. My Drupal website is multilingual, and on one view page we present some content in Default language, by typing in the textfield some other language, I need to change the language of the content. For this I created a filter (Translation language = Content language selected for a page), and I want to expose it in a custom block.

My custom block looks like following:

 * @file
 * Contains \Drupal\filters\Plugin\Block\FilterLanguages.php
namespace Drupal\filters\Plugin\Block;

use Drupal\Core\Block\BlockBase;

 * @Block(
 *   id = "block_filters_languages",
 *   admin_label = @Translation("Filter for languages"),
 *   category = @Translation("Filters"),
 * )
class FilterLanguages extends BlockBase {

   * {@inheritdoc}

public function build(){

$form['language'] = array(
  '#type' => 'textfield',
  '#placeholder' => t('Choose language autocomplete'),
  '#autocomplete_route_name' => 'filters.autocomplete',


return $form;

To provide autocompletion option, I have created routing file:

  path: '/filters/autocomplete'
    _access: 'TRUE'

And Controller:

namespace Drupal\filters\Controller;

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

class AutocompleteController extends ControllerBase{
   * Returns response for the autocompletion.
  public function handleAutocomplete(Request $request) {

    $languages = \Drupal::languageManager()->getLanguages();
    return new JsonResponse($languages);

I have oriented on the followin tutorial But the autocompletion still doesnt work. Could you please help me to solve the problem?


You need to filter the user input and return the matches.

  public function handleAutocomplete(Request $request) {
    // Getting the user input.
    $string = $request->query->get('q');
    // Getting the languages.
    $languages = \Drupal::languageManager()->getLanguages();
    // Getting the matches.
    $matches = preg_grep("/$string/i", $languages);
    // Returning the matches.
    return new JsonResponse($matches);
|improve this answer|||||
  • Thanks a lot for your answer. The issue for me that I still can not search through my textfield. If I type something in, it doesn't offer me any options – user91143 Feb 4 '19 at 9:10
  • Do I need any additional JS scripts to make it work? Like here – user91143 Feb 4 '19 at 10:01
  • @user91143 no, you don't need another javascript – Adrian Cid Almaguer Feb 4 '19 at 17:01

Your Answer

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