I am building a custom autocomplete field. 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'.
When users type a, it should show Apple, Avocado. Clicking on any of them, it should show Apple, not fruit-1 in the field.
This is the code I am using.
Form
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
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 shows the fruits label (Apple), but when I click on the fruit label, the field value shows fruit-1. I want to show Apple when users select Apple.
PS: I don't want to use the same value for label and value.
$results = [['value' => 'Apples', 'label' => 'Apples'], ['value' => 'Apricots', 'label' => 'Apricots'], ['value' => 'Avocados', 'label' => 'Avocados']];