I 've a problem with Drupal 8 ajax callbacking. I created a multivalue field for country - region listing as new field type using a custom module. In first selectlist I loaded all country codes and I set this field as multivalued.

I wrote the below code in FieldWidgetType Class.

     public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element['value'] =  array(
      '#type' => 'select',
      '#title' => 'Select Country', 
      '#name' => 'value',   
      '#options' => array(
        0 => t('- Select Country -')) + $termNameArr,
      '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
      '#ajax' => [
              'callback' => array($this, '_regions_ajax_callback'),
              'event' => 'change',
              'progress' => array(
                 'type' => 'throbber',
                 'message' => t('Please wait.Fetching data...'),
      '#suffix' => '<span class="email-valid-message"></span>'
    return $element;

I have to load regions of the selected country in an another select box using ajax. The selectbox should populate with the regions of selected country in change event of country select box item (here I'm calling ajax). Or else, can ajax simply return the selected country value to append in span (.email-valid-message) specified in #suffix.

My current callback to return at least the selected country name is:

    public function _regions_ajax_callback(&$form, &$form_state) {
      $response = new AjaxResponse();
      $element = $form['value'];
      $default_value = isset($element['#default_value']) ? element['#default_value'] : NULL;
      $value = $form_state->getValue($element['#name']);
      $changed = $default_value == $value;
        if ($changed) {
       $response->addCommand(new HtmlCommand('.email-valid-message', $value));
    return $response;

I used namespaces

    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\HtmlCommand;

What am I doing wrong? How can I change my callback function to get current field value? Did I miss to add any namespace?

  • I guess issue in your callback's parameters? Commented Mar 16, 2016 at 5:06

2 Answers 2


in your _regions_ajax_callback()

$element = $form_state->getTriggeringElement();
element['#value'] <-- value is in here
  • This is not the case for me, my element's #value is empty.
    – akalata
    Commented Jun 12, 2019 at 17:08

I did by using getUserInput()


  public function myAjaxCallback(array &$form, FormStateInterface $form_state) {

    $input = $form_state->getUserInput();
    $input = $input['field-name-goes-here'];

    // Sanitize input.
    $input = Xss::filter($input);


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.