3

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? – Sumit Madan Mar 16 '16 at 5:06
3

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 Jun 12 at 17:08

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.