You are here

protected static function ZoneTerritory::buildSubdivisionElements in Address 8

Builds the subdivision form elements.

Parameters

array $element: The existing form element array.

array $value: The element value.

\CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format: The address format for the selected country.

Return value

array The form with the added subdivision elements.

1 call to ZoneTerritory::buildSubdivisionElements()
ZoneTerritory::processTerritory in src/Element/ZoneTerritory.php
Processes the zone territory form element.

File

src/Element/ZoneTerritory.php, line 177

Class

ZoneTerritory
Provides a zone territory form element.

Namespace

Drupal\address\Element

Code

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

    // No predefined data found.
    return $element;
  }
  $labels = LabelHelper::getFieldLabels($address_format);
  $subdivision_fields = $address_format
    ->getUsedSubdivisionFields();
  $current_depth = 1;
  $parents = [];
  foreach ($subdivision_fields as $index => $field) {
    $property = FieldHelper::getPropertyName($field);
    $parent_property = $index ? FieldHelper::getPropertyName($subdivision_fields[$index - 1]) : 'country_code';
    if ($parent_property && empty($value[$parent_property])) {

      // No parent value selected.
      break;
    }
    $parents[] = $value[$parent_property];
    $subdivisions = \Drupal::service('address.subdivision_repository')
      ->getList($parents);
    if (empty($subdivisions)) {
      break;
    }
    $element[$property] = [
      '#type' => 'select',
      '#title' => $labels[$field],
      '#options' => $subdivisions,
      '#default_value' => $value[$property],
      '#empty_option' => t('- All -'),
    ];
    if ($current_depth < $depth) {
      $element[$property]['#ajax'] = [
        'callback' => [
          get_called_class(),
          'ajaxRefresh',
        ],
        'wrapper' => $element['#wrapper_id'],
      ];
    }
    $current_depth++;
  }
  return $element;
}