Populating Select2 with AJAX I am trying to populate a selec2 field on open with AJAX in Drupal 8. In my hook_form_alter, I have added the following code:
  $form['#prefix'] = '&lt;div id=&quot;form-ajax-wrapper&quot;&gt;';
  $form['#suffix'] = '&lt;/div&gt;';

  $form['field_author']['widget']['#ajax'] = [
    'callback' =&gt; 'myPopulate',
    'wrapper' =&gt; 'form-ajax-wrapper',
    'event' =&gt; 'select2:opening',
  ];

which correctly calls to the callback function when I try to open the drop-down list:
function reloadOptions(array $form, FormStateInterface $form_state){
  $query = \Drupal::entityQuery('node');
  $query-&gt;condition('type', 'author');
  $query-&gt;condition('status', 1);
  $nids = $query-&gt;execute();
  $nodes = Node::loadMultiple($nids);

  foreach ($nodes as $node) {
    $options[$node-&gt;id()] = FieldFilteredMarkup::create($node-&gt;getTitle());
  }

  $form['field_author']['widget']['#options'] = $options;

  return $form;
}

The query is ok, and the way in which the options are loaded also seems ok. However, when I click on the selec2 field to open it, the ajax throbber is shown but the drop-down list does not open.
Any ideas why is this happening?
Thanks!
EDIT:
A capture of the behaviour of the selector2. As you can see, the drop-down list is not displayed after you click. However, if the ajax call is removed, it works correctly.
The ajax callback is pointing to the wrong function, should be:
callback' =&gt; 'reloadOptions',

It's better to make it return just the field rather than the entire form
$form['field_author']['#prefix'] = '&lt;div id=&quot;author-ajax-wrapper&quot;&gt;';
$form['field_author']['#suffix'] = '&lt;/div&gt;';

$form['field_author']['widget']['#ajax'] = [
  'callback' =&gt; 'reloadOptions',
  'wrapper' =&gt; 'author-ajax-wrapper',
  'event' =&gt; 'select2:opening',
];

Adjust the reloadOptions fuction, so it returns just the specific field
return $form['field_author'];