You are here

protected static function Address::processSubdivisionElements in Address 8

Processes the subdivision elements, adding predefined values where found.

Parameters

array $element: The existing form element array.

array $value: The address value, in $property_name => $value format.

\CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format: The address format.

Return value

array The processed form element array.

1 call to Address::processSubdivisionElements()
Address::addressElements in src/Element/Address.php
Builds the format-specific address elements.

File

src/Element/Address.php, line 298

Class

Address
Provides an address form element.

Namespace

Drupal\address\Element

Code

protected static function processSubdivisionElements(array $element, array $value, AddressFormat $address_format) {
  $depth = $address_format
    ->getSubdivisionDepth();
  if ($depth === 0) {

    // No predefined data found.
    return $element;
  }
  $subdivision_properties = [];
  foreach ($address_format
    ->getUsedSubdivisionFields() as $field) {
    $subdivision_properties[] = FieldHelper::getPropertyName($field);
  }

  // Load and insert the subdivisions for each parent id.
  $locale = \Drupal::languageManager()
    ->getConfigOverrideLanguage()
    ->getId();
  $current_depth = 1;
  $parents = [];
  foreach ($subdivision_properties as $index => $property) {
    if (!isset($element[$property]) || !Element::isVisibleElement($element[$property])) {
      break;
    }
    $parent_property = $index ? $subdivision_properties[$index - 1] : 'country_code';
    if ($parent_property && empty($value[$parent_property])) {
      break;
    }
    $parents[] = $value[$parent_property];
    $subdivisions = \Drupal::service('address.subdivision_repository')
      ->getList($parents, $locale);
    if (empty($subdivisions)) {
      break;
    }
    $element[$property]['#type'] = 'select';
    $element[$property]['#options'] = $subdivisions;
    $element[$property]['#empty_value'] = '';
    unset($element[$property]['#size']);
    if ($current_depth < $depth) {
      $element[$property]['#ajax'] = [
        'callback' => [
          get_called_class(),
          'ajaxRefresh',
        ],
        'wrapper' => $element['#wrapper_id'],
      ];
    }
    $current_depth++;
  }
  return $element;
}