0

How to make ajax work inside hook_field_widget_form()

    /**
      * Implements hook_field_widget_form().
     */
        function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      $form_field['autocomplete'] = array(
        '#type' => 'textfield',
        '#title' => 'Tags',
        '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => 1024,
        '#element_validate' => array('taxonomy_autocomplete_validate'),
        '#prefix' => '<div id ="subscribers-name">',
        '#suffix' => '</div>',
      );
      if (isset($form_state['values']['autocomplete'])) {
        $form_field['autocomplete']['#value'] = 'new value';
      }

      $form_field['search_tags'] = array(
        '#type' => 'button',
        '#value' => 'Recommend Tags',
        '#ajax' => array(
          'callback' => 'call_ajax_replace_value',
          'wrapper' => 'subscribers-name',
          'method' => 'replace',
        ),
      );
      $element += $form_field;
      return $element;
    }

    function call_ajax_replace_value($form, &$form_state) {
       return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
    }

How do i update autocomplete textfield value on AJAX callback?

1 Answer 1

2
+50

Just assign the value in callback function.

/**
 * Implements hook_field_widget_form().
 */
function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $form_field['autocomplete'] = array(
    '#type' => 'textfield',
    '#title' => 'Tags',
    '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#prefix' => '<div id ="subscribers-name">',
    '#suffix' => '</div>',
  );

  $form_field['search_tags'] = array(
    '#type' => 'button',
    '#value' => 'Recommend Tags',
    '#ajax' => array(
      'callback' => 'call_ajax_replace_value',
      'wrapper' => 'subscribers-name',
      'method' => 'replace',
    ),
  );
  $element += $form_field;
  return $element;
}

function call_ajax_replace_value($form, &$form_state) {
  if (isset($form_state['values']['autocomplete'])) {
    $form_field['autocomplete']['#value'] = 'new value';
  }
  return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.