2

I was making a custom autocomplete field and it worked as in when I type 'a' it shows me all the list of fruits with letter 'a'. But when I click on any of the options. I see the autocomplete field 'value'.

I want the functionality where when user types 'a' it should show 'Apple', 'Avocado'. and on clicking any of it should show label 'Apple' not 'fruit-1' in the field.

Following is the code:

Custom form:

<?php
/**
 * @file
 * Contains \Drupal\custom_google_search\Form\GoogleSearchAutocomplete.
 */

namespace Drupal\custom_google_search\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;

class GoogleSearchAutocomplete extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'custom_google_search_autocomplete';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['google_places_search'] = [
      '#type' => 'textfield',
      '#title' => t('Searchfield'),
      '#autocomplete_route_name' => 'custom_google_search.autocomplete',
      '#value' => 'aaa11',
    ];
  $form['search_in_us'] = [
    '#type' => 'submit',
    '#value' => $this->t('Search'),
    ];
      return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }
}

Autocomplete controller:

<?php
/**
 * @file
 * Autocomplete controller for custom google search
 */

namespace Drupal\custom_google_search\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Component\Utility\Tags;
use Drupal\Component\Utility\Unicode;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

class AutocompleteController extends ControllerBase {

  public function handleAutocomplete(Request $request) { 
    // 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));
      $trimed_string = preg_replace("/\s+/", "+", $typed_string);
      $results = $this->showRelatedPlaces($trimed_string);
    }
    return new JsonResponse($results);
  }

  public function showRelatedPlaces($trimed_string) {
    try {
       $results = [
         [
           'value' => 'fruit-1',
           'label' => 'Apples',
         ],
         [
           'value' => 'fruit-2',
           'label' => 'Apricots',
         ],
         [
           'value' => 'fruit-3',
           'label' => 'Avocados',
         ],
       ];
      return($results);
    } catch (RequestException $e) {
    return($this->t('Error occured.'));
  }
 }  
}

Problem is that when I type 'a' in the autocomplete textfield. It does show me the fruits label (Apple) but when I click on the fruit label. The field value shows 'fruit-1'. I want to show 'Apple' when a user selects an option.

PS: I don't want to use the same value for label and value. (Apple for both label and value).

  • 1
    Welcome to Drupal Answers! If you are referring to an autocomplete field you created from a custom module, you need to show the code you are using, or we cannot tell you what is wrong in the code you are using. Plus, the question would not be much helpful to future users, which what one of the purposes Stack Exchange sites have. – kiamlaluno Apr 7 '18 at 18:48
0

Make value and label are same

$results = [ [ 'value' => 'Apples', 'label' => 'Apples', ], [ 'value' => 'Apricots', 'label' => 'Apricots', ], [ 'value' => 'Avocados', 'label' => 'Avocados', ], ];

0

Unfortunately, this is how the Drupal 8/JQuery.ui autocomplete operates.

In the select callback for the autocomplete, you could unset the value/user input on the field, store it in storage on the form_state and then pull the label by the value and add it in the buildForm() method. Or you could try to use some hacky JQuery/JavaScript to get around it.

The way Drupal has done this in the past (with the Entity Reference module in Drupal 7 for example) is by setting the value in the label as well (in parentheses/square brackets) and then pulling the value off the label when it's needed through RegEx.

The problem with setting the value AS the label as Selvakumar answered, is that you'll never have the value available to you to use.

Of course, if someone does have a proper solution to this I am all ears!

EDIT: I figured something out, and posted it here Autocomplete textfield displays value when selected and not label

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.