1

I am trying to use autocomplete in a custom form, but I don't know how to pass the current value of the field to the autocomplete function.

This is my form element:

  $form['gs_name'] = [
    '#type' => 'textfield',
    '#title' => $this->t("Name"),
    '#autocomplete_route_name' => 'gseight_autocomplete',
    //'#autocomplete_parameters' => array(),
    '#required' => TRUE,
  ];

Route:

gseight_autocomplete:
  path: 'gseight_autocomplete'
  defaults:
    _controller: '\Drupal\gseight\Controller\GsEightAutoComplete::content'
    _title: 'Autocomplete Results'
  requirements:
    _permission: 'access GS simple page'

Inside GsEightAutoComplete

public function content($q = '') {

    //get user
    $userCurrent = \Drupal::currentUser();
    $uid = $userCurrent->id();

    $selectthree = db_select('gs_plans','g');
    $selectthree->addField('g','gs_name');
    // Filter only current user".
    $selectthree->condition('g.uid', $uid);
    $selectthree->condition('g.gs_name', '%' . db_like($q) . '%', 'LIKE');

    $currentone = $selectthree->execute()->fetchAll();

    $jsonarray = array();

    foreach($currentone as $eachcurrentone) {
        $jsonarray[] = $eachcurrentone->gs_name;
    }

    return new JsonResponse($jsonarray);

    }

The array fills with items from the database that belong to the current user when i have $q = ''at the start. But how do I pass the current value of the field to q?

1 Answer 1

3

The form value is automagically added as a query parameter so it is not necessary to pass the current value. This is accessible in the Request object. The controller class method should be:

public function autocomplete(\Symfony\Component\HttpFoundation\Request $request) {
  $value = $request->query->get('q');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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