My use case is the following : I've an autocomplete widget to a referenced entity and I want the value of an other autocomplete widget to be selected when the first one is done.

I'm aware of this topic and of the autocompleteclose ajax event, but was not able to see any ajax request fired in the browser's console.

Since it's my first attempt to altering drupal's forms and using its AJAX API, I decided to try the simplyest test as possible on a text field, but, was still not able to see any ajax request in my browser's console... Here's my example code :

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id){
    $form['my_field']['#ajax'] = array(
        'event' => 'change',
        'callback' => 'my_ajax_callback',
        'wrapper' => 'my-wrapper',
    $form['my_field']['#attributes'] = array('style' => 'color:red');

I can see my form is altered because my field label is red... But when I type in it, the ajax callback is not triggered and I do not see any error in the console.

Jquery lib is loaded and ajax is working because I can see ajax requests when using autocomplete fields... Anyway I tried to attach the drupal core ajax lib as mentionned in this post ($form['#attached']['library'][] = 'core/drupal.ajax';), but nothing changed...

I'm obviously missing something here... Has anybody an idea ?

  • You need to look at $form['my_field']'s children - $form['my_field'] itself will be a wrapper, hence adding classes applies the desired CSS, but the AJAX needs to be applied to the widget itself, which is further down the hierarchy. Same sort of principle as drupal.stackexchange.com/questions/27767 – Clive Mar 17 '17 at 12:05
  • Hi @Clive, I've tried to add the '#ajax' array to the widget children When I use dump($form['field_subtitle']['widget']['#ajax']), it outputs the following array : "event" => "change", "callback" => "my_ajax_callback", "wrapper" => "my-wrapper", but there is still no ajax request fired... Have you got an idea ? Thanx for helping by the way... – Kap Mar 17 '17 at 12:51
  • Did you manage to resolve this issue? – David May 2 '17 at 8:53
  • Yes ! I had to use the following to target the form field : $form['my_field']['widget'][0]['target_id']['#ajax']. Doing that way the ajax request was fired. Hope this helps... – Kap May 4 '17 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.