I have a form element of "entity_autocomplete" type. Also I have an ajax callback of the element. Here is its code.

$form['autocomplete_places'] = [
            '#type' => 'entity_autocomplete',
            '#target_type' => 'node',
            '#selection_settings' => [
                'target_bundles' => ['place'],
            '#ajax' => [
                'callback' => '::autocompleteGetPlaces',
                'event' => 'autocompleteselect',

public function autocompleteGetPlaces(array &$form, FormStateInterface $form_state){
        $ajax_responce = new AjaxResponse();
/// some code here 
        return $ajax_responce;

Unfortunately, I can't find out how to get the id of selected entity inside the ajax callback function. For example, in my case, it would be id of a node of "place" type.

I tried to debug it, but couldn't find information about it in $form_state.

Could you clarify me, how to do it ?


Seemingly I managed to find the solution.

The event for the autocomplete element should be "autocompleteclose" instead "autocompleteselect". And in this case it's possible to get entity_id via

$entity_id = $form_state->getValue('autocomplete_places');

if the list of values was closed without selected element then $form_state->getValue('autocomplete_places') is null.

| improve this answer | |

Take a look at: $form_state->getUserInput()

Depending on the structure of your form, one of the following may work:

$parents = array_merge($form['#parents'], ['autocomplete_places', '0', 'target_id']);

-- or --

$parents = array_merge($form['#parents'], ['autocomplete_places']);

Then you can get the autocomplete full text with this:

$input_value = NestedArray::getValue($form_state->getUserInput(), $parents);

Then you can parse the $input_value string to get the node id portion of the user input.

| improve this answer | |
  • Unfortunately, your solution doesn't work. But I found the working solution and described it in my answer. – Yakimkin Roman Aug 31 '17 at 19:24

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.