Drupal quick tip of the day: the "autocompleteclose" event

Today I want to introduce you to the lesser known "autocompleteclose" event that you can use for Ajax callbacks in Drupal's Form API.

When I was defining an entity_autocomplete field in a form and tried to add an Ajax callback, that should modify other form fields based on the selection of the autocomplete field, my first implementation had got the blemish to react on the "change" event, meaning that after you have selected an entity via the autocomplete field, you first would have to leave the field (e.g by pressing the tab key or click/tabe somewhere else on the page). I was then trying to find an appropriate event that is fired upon selecting a value from the autocomplete field.

I finally found the solution in Drupal's issue queue. So here's a short example:


    $entity_form['my_wonderful_field'] = [
      '#type' => 'entity_autocomplete',
      '#title' => t('Choose xy'),
      '#target_type' => 'node',
      '#selection_settings' => [
        'match_operator' => 'CONTAINS',
      ],
      '#ajax' => [
        'callback' => [$this, 'onNodeSelection'],
        'wrapper' => $wrapper_id,
        'event' => 'autocompleteclose',
      ],
      '#maxlength' => 512,
    ];

 

Wanted - your help!

In a similar case, I'm currently banging my head against the wall: I'm using Entity Browser for a certain reference field, and I also want to react on the selection. But there's one big difference in this use case: the (hidden) field that is defined and used by Entity Browser to hold the selected entity ID, of course already defines its own #ajax callback. You can't add a second one. Although being able to identify the selection event within my form cleanly, I find no way to react on it, as the fields I want to change, are not part of the wrapper element that is replaced by the Ajax call. So changing anything there would not result in any visible change in the UI.

What I try to avoid is to fully replace the Ajax callback and repeat the logic of the Entity Browser's original callback + add my own stuff. Additionally, I still would have to see if there's a chance to unite them all into a single wrapper element - if not, I'd have to additonally build my own Ajax response and replicate Drupal's internal logic here.

I've opened a support request in Entity Browser's issue queue with a more detailed description of my problem. I'd really appreciate any help!

Neuen Kommentar schreiben