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?