You are here

public static function Address::clearValues in Address 8

Clears dependent form values when the country or subdivision 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/Address.php, line 394

Class

Address
Provides an address 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',
      'postal_code',
      'sorting_code',
    ],
    '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;
}