You are here

public static function ZoneTerritory::clearValues in Address 8

Clears the country-specific form values when the country changes.

Implemented as an #after_build callback because #after_build runs before validation, allowing the values to be cleared early enough to prevent the "Illegal choice" error.

File

src/Element/ZoneTerritory.php, line 311

Class

ZoneTerritory
Provides a zone territory form element.

Namespace

Drupal\address\Element

Code

public static function clearValues(array $element, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();
  if (!$triggering_element) {
    return $element;
  }
  $keys = [
    'country_code' => [
      'dependent_locality',
      'locality',
      'administrative_area',
    ],
    'administrative_area' => [
      'dependent_locality',
      'locality',
    ],
    'locality' => [
      'dependent_locality',
    ],
  ];
  $triggering_element_name = end($triggering_element['#parents']);
  if (isset($keys[$triggering_element_name])) {
    $input =& $form_state
      ->getUserInput();
    foreach ($keys[$triggering_element_name] as $key) {
      if (isset($element[$key])) {
        $parents = array_merge($element['#parents'], [
          $key,
        ]);
        NestedArray::setValue($input, $parents, '');
        $element[$key]['#value'] = '';
      }
    }
  }
  return $element;
}