0

I need to alter the address field because I want to transform the locality textfield in a nested select box along with administrative_area value.

I've tried to do that with a hook widget_alter, form alter, after_build callback, but any of them run my ajax callback.

Here is what I'm trying to do:

function ffcore_field_widget_address_default_form_alter(&$element, FormStateInterface $form_state, $context) {
  $element['address']['#after_build'][] = 'ffcore_validate_cities';
}

function ffcore_validate_cities(array $element, FormStateInterface $form_state) {

  foreach (Element::getVisibleChildren($element) as $key) {
    if (!empty($element[$key]['#required'])) {
      $element[$key]['#required'] = FALSE;
    }
  }
  $element['locality']['#weight'] = 1;
  $element['locality']['#prefix'] = '<div id="change-city-list">';
  $element['locality']['#suffix'] = '</div>';
  $element['administrative_area']['#weight'] = 0;
  $element['administrative_area']['#ajax'] = [
    'callback' => 'ffcore_change_cities_by_dept',
    'event' => 'change',
    'wrapper' => 'change-city-list',
  ];
  return $element;
}

function ffcore_change_cities_by_dept(array $form, FormStateInterface $form_state) {
  return $form['locality'];
}

In that way, I can change the order of the fields, but I can't use the ajax callback.

Is there any other way to achieve that?

3
  • If you're using Drupal 8, I find it much easier to alter things by extending classes vs using alter hooks. In this case you'd have to extend the Field Widget that's controlling your address field, then configure your Form Display to use your new widget. I don't know if this would help here or make it easier, but I generally find it an easier place to work and debug from.
    – sonfd
    Commented Jun 25, 2020 at 11:15
  • Do you see any error messages in your console? When viewing the field on the front end, do you see your change-city-list div added to the form around the locality field?
    – sonfd
    Commented Jun 25, 2020 at 11:16
  • I also tried creating my own Field Widget from the original one, but the issue is that only a part of the field is rendered in formElement method, apparently, there is another part where the rest of the form is created. It has its own Element call Adress but y don't know how to alter it. In console I see nothing and the wrapper is added. Commented Jun 25, 2020 at 13:59

0

Your Answer

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

Browse other questions tagged or ask your own question.