1

I need to store a country and a region for geographical objects. Countries and regions are stored in a taxonomy vocabulary. Moreover, some countries have regions (as child terms) but someones don't have it.

I decided to create a complex field contains tid of a country and tid of a region. If an object doesn't have a set region, then a value of the region is 0 in this case.

I want to create a field widget for it. The widget should contain a combo box with a list of countries. Moreover, if the user is selected a country having regions, then a new combo box with its regions is appeared.

I have tried to do it with ajax like it is done in forms.

That is, I have written the following. (Here I have removed some code from the source to shorten it)

  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
  {

// come code here ....

    // TODO: Implement formElement() method.
    $element['country_id'] = [
      '#type' => 'select',
      '#title' => t('Select a country'),
      '#options' => PalomGeo::getCountryList(),
      '#default_value' => $country_id,
      '#ajax' => [
        'callback' => '::changeCountry',
      ]
    ];

    $regions = PalomGeo::getRegionList($country_id);

    if ($regions!=[]){
      $element['region_id'] = [
        '#type' => 'select',
        '#title' => t('Select a region'),
        '#options' => $regions,
        '#default_value' => $region_id,
      ];
    }

    return $element;
  }

// Some code here

  public function changeCountry(array &$form, FormStateInterface $form_state){
    return $form['region_id'];
  } 

But unfortunately, it doesn't work.

The error "The specified #ajax callback is empty or not callable" is appeared.

I want to clarify is it possible to use AJAX upon creating field widgets? If yes, does it differ from using AJAX in Drupal 8 Forms?

2

You need to specify the class (including the full namespace) to run that method on. E.g: 'callback' => \Drupal\my_module\Plugin\Field\FieldWidget\MyWidget::changeCountry

  • For me, this threw an error if changeCountry was declared as in the question: Deprecated function: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Drupal\my_module\Plugin\Field\FieldWidget\MyWidget::changeCountry() should not be called statically. It was easily resolved by changing the callback value to 'callback' => [$this, 'changeCountry']. – Paul Mar 6 at 11:19

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.