Score:0

entity_autocomplete attached via #ajax callback doesn't work

sa flag

I'm serving an entity_autocomplete field via #ajax callback when a checkbox in the form is unchecked.

The entity_autocomplete field shows but there is no autocomplete attached to it.

Here is how I attached it from within ajax callback:

$form['url_301'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
  '#required' => TRUE,
  '#prefix' => '<div id="edit-output">',
  '#suffix' => '</div>',
];
$form['url_301'] = EntityAutocomplete::processEntityAutocomplete($form['url_301'], $form_state, $form);

return $form['url_301'];

How can I resolve this?

Score:0
sa flag

Found a solution.

The entity_autocomplete field should be prepared/set within hook_form_alter(), not within ajax_callback()

And it should be returned within ajax_callback().

Here is an example:

function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $status = $form_state->getValue('status')['value'];

  if ($status === 0) {

    $form['url'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#title' => t('My autocomplete field'),
      '#required' => TRUE,
      '#prefix' => '<div id="edit-output">',
      '#suffix' => '</div>',
    ];

  }

  $form['output'] = [
    '#markup' => 'Output',
    '#prefix' => '<div id="edit-output">',
    '#suffix' => '</div>',
    '#weight' => 100,
  ];

  $form['status']['widget']['value']['#ajax'] = [
    'callback' => '_my_ajax_callback',
    'event' => 'change',
    'wrapper' => 'edit-output',
    'progress' => [
      'type' => 'throbber',
      'message' => 'Processing...',
    ],
  ];
}

function _my_ajax_callback(array &$form, FormStateInterface $form_state) {

  $status = $form_state->getValue('status')['value'];

  if ($status == 0) {
    return $form['url'];
  }
  else {
    return [
      '#prefix' => '<div id="edit-output">',
      '#suffix' => '</div>',
    ];
  }
}
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.