1

I have implemented a custom form. I put same Ajax callback function for multiple field. When one Ajax call completes, I click on other field. But I can't unfocused previous field. Sometimes the Ajax call runs for multiple field.

My code:

$form['worklocation'] = array(
    '#title' => t('Work Location'),
    '#type' => 'textfield',

   '#autocomplete_route_name' => 'advance_search_autocomplete_callback.advancesearch_autocomplete_callback',
    '#autocomplete_route_parameters' => array('type' => 'worklocation'),
    '#ajax' => array(
      'callback' => [$this, 'friends_advance_search_results'],
    ),
    '#attributes' => array('class' => array('form-control')),

  );

  $form['school'] = array(
    '#title' => t('School'),
    '#type' => 'textfield',

    '#autocomplete_route_name' => 'advance_search_autocomplete_callback.advancesearch_autocomplete_callback',
    '#autocomplete_route_parameters' => array('type' => 'school'),
    '#ajax' => array(
      'callback' => [$this, 'friends_advance_search_results'],
    ),
    '#attributes' => array('class' => array('form-control')),

  );
  $form['college'] = array(
    '#title' => t('College / University'),
    '#type' => 'textfield',

   '#autocomplete_route_name' => 'advance_search_autocomplete_callback.advancesearch_autocomplete_callback',
    '#autocomplete_route_parameters' => array('type' => 'college'),
    '#ajax' => array(
      'callback' => [$this, 'friends_advance_search_results'],
    ),
    '#attributes' => array('class' => array('form-control')),

  );

Callbakck:

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

 $search_result = array(
                    '#theme' => 'friends_advanced_search_list',
                    '#friends' => $friends_list,
                    '#info' => array('display' => 'hide', 'friend_recommend' => 0, 'load_more' => $load_more, 'no_results' => 1,'search_action' => 1),

                    );

   $output = render($search_result);
   $id = '#advanced-friend-list';
   $response = new AjaxResponse();
   $response->addCommand(new ReplaceCommand($id, $output)); 

   return $response; 

}

Problem: enter image description here

  • And what happens when you use different functions for every callback? – leymannx Jun 28 at 6:25
  • '#ajax' => [ 'callback' => [$this, 'friends_advance_search_results'], 'disable-refocus' => TRUE, ], I missed – Arif Jun 28 at 7:07
2

Enable disable-refocus when adding the ajax callback:

'#ajax' => [
  'callback' => [$this, 'friends_advance_search_results'],
  'disable-refocus' => TRUE,
],

See https://www.drupal.org/project/drupal/issues/2627788

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.