Address.php 13.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
<?php

namespace Drupal\address\Element;

use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressFormatHelper;
use CommerceGuys\Addressing\LocaleHelper;
use Drupal\address\FieldHelper;
use Drupal\address\LabelHelper;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\SortArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;

/**
 * Provides an address form element.
 *
 * Usage example:
 * @code
 * $form['address'] = [
 *   '#type' => 'address',
 *   '#title' => $this->t('Address'),
 *   '#default_value' => [
 *     'given_name' => 'John',
 *     'family_name' => 'Smith',
 *     'organization' => 'Google Inc.',
 *     'address_line1' => '1098 Alta Ave',
 *     'postal_code' => '94043',
 *     'locality' => 'Mountain View',
 *     'administrative_area' => 'CA',
 *     'country_code' => 'US',
 *     'langcode' => 'en',
 *   ],
 *   '#available_countries' => ['DE', 'FR'],
 * ];
 * @endcode
 *
 * @FormElement("address")
 */
class Address extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      // List of country codes. If empty, all countries will be available.
      '#available_countries' => [],
      // List of AddressField constants. If empty, all fields will be used.
      '#used_fields' => [],

      '#input' => TRUE,
      '#multiple' => FALSE,
      '#process' => [
        [$class, 'processAddress'],
        [$class, 'processGroup'],
      ],
      '#pre_render' => [
        [$class, 'groupElements'],
        [$class, 'preRenderGroup'],
      ],
      '#after_build' => [
        [$class, 'clearValues'],
      ],
      '#attached' => [
        'library' => ['address/form'],
      ],
      '#theme_wrappers' => ['container'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if (is_array($input)) {
      return $input;
    }
    else {
      if (!is_array($element['#default_value'])) {
        $element['#default_value'] = [];
      }
      // Initialize properties.
      $properties = [
        'given_name', 'additional_name', 'family_name', 'organization',
        'address_line1', 'address_line2', 'postal_code', 'sorting_code',
        'dependent_locality', 'locality', 'administrative_area',
        'country_code', 'langcode',
      ];
      foreach ($properties as $property) {
        if (!isset($element['#default_value'][$property])) {
          $element['#default_value'][$property] = NULL;
        }
      }

      return $element['#default_value'];
    }
  }

  /**
   * Processes the address form element.
   *
   * @param array $element
   *   The form element to process.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   *
   * @return array
   *   The processed element.
   *
   * @throws \InvalidArgumentException
   *   Thrown when #available_countries or #used_fields is malformed.
   */
  public static function processAddress(&$element, FormStateInterface $form_state, &$complete_form) {
    if (isset($element['#available_countries']) && !is_array($element['#available_countries'])) {
      throw new \InvalidArgumentException('The #available_countries property must be an array.');
    }
    if (isset($element['#used_fields']) && !is_array($element['#used_fields'])) {
      throw new \InvalidArgumentException('The #used_fields property must be an array.');
    }

    $id_prefix = implode('-', $element['#parents']);
    $wrapper_id = Html::getUniqueId($id_prefix . '-ajax-wrapper');
    $full_country_list = \Drupal::service('address.country_repository')->getList();
    $country_list = $full_country_list;
    if (!empty($element['#available_countries'])) {
      $available_countries = $element['#available_countries'];
      $available_countries = array_combine($available_countries, $available_countries);
      $country_list = array_intersect_key($country_list, $available_countries);
    }

    $value = $element['#value'];
    if (empty($value['country_code']) && $element['#required']) {
      // Fallback to the first country in the list if the default country
      // is empty even though the field is required.
      $value['country_code'] = key($country_list);
    }
    if (!empty($value['country_code']) && !isset($country_list[$value['country_code']])) {
      // This item's country is no longer available. Add it back to the top
      // of the list to ensure all data is displayed properly. The validator
      // can then prevent the save and tell the user to change the country.
      $missing_element = [
        $value['country_code'] => $full_country_list[$value['country_code']],
      ];
      $country_list = $missing_element + $country_list;
    }

    $element += [
      '#prefix' => '<div id="' . $wrapper_id . '">',
      '#suffix' => '</div>',
      // Pass the id along to other methods.
      '#wrapper_id' => $wrapper_id,
    ];
    $element['langcode'] = [
      '#type' => 'hidden',
      '#value' => $value['langcode'],
    ];
    // Hide the country dropdown when there is only one possible value.
    if (count($country_list) == 1 && $element['#required']) {
      $element['country_code'] = [
        '#type' => 'hidden',
        '#value' => key($available_countries),
      ];
    }
    else {
      $element['country_code'] = [
        '#type' => 'select',
        '#title' => t('Country'),
        '#options' => $country_list,
        '#default_value' => $value['country_code'],
        '#required' => $element['#required'],
        '#limit_validation_errors' => [],
        '#ajax' => [
          'callback' => [get_called_class(), 'ajaxRefresh'],
          'wrapper' => $wrapper_id,
        ],
        '#attributes' => [
          'class' => ['country'],
          'autocomplete' => 'country',
        ],
        '#weight' => -100,
      ];
      if (!$element['#required']) {
        $element['country_code']['#empty_value'] = '';
      }
    }
    if (!empty($value['country_code'])) {
      $element = static::addressElements($element, $value);
    }

    return $element;
  }

  /**
   * Builds the format-specific address elements.
   *
   * @param array $element
   *   The existing form element array.
   * @param array $value
   *   The address value, in $property_name => $value format.
   *
   * @return array
   *   The modified form element array containing the format specific elements.
   */
  protected static function addressElements(array $element, array $value) {
    $size_attributes = [
      AddressField::ADMINISTRATIVE_AREA => 30,
      AddressField::LOCALITY => 30,
      AddressField::DEPENDENT_LOCALITY => 30,
      AddressField::POSTAL_CODE => 10,
      AddressField::SORTING_CODE => 10,
      AddressField::GIVEN_NAME => 25,
      AddressField::ADDITIONAL_NAME => 25,
      AddressField::FAMILY_NAME => 25,
    ];
    /** @var \CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format */
    $address_format = \Drupal::service('address.address_format_repository')->get($value['country_code']);
    $required_fields = $address_format->getRequiredFields();
    $labels = LabelHelper::getFieldLabels($address_format);
    $locale = \Drupal::languageManager()->getConfigOverrideLanguage()->getId();
    if (LocaleHelper::match($address_format->getLocale(), $locale)) {
      $format_string = $address_format->getLocalFormat();
    } else {
      $format_string = $address_format->getFormat();
    }
    $grouped_fields = AddressFormatHelper::getGroupedFields($format_string);
    foreach ($grouped_fields as $line_index => $line_fields) {
      if (count($line_fields) > 1) {
        // Used by the #pre_render callback to group fields inline.
        $element['container' . $line_index] = [
          '#type' => 'container',
          '#attributes' => [
            'class' => ['address-container-inline'],
          ],
        ];
      }

      foreach ($line_fields as $field_index => $field) {
        $property = FieldHelper::getPropertyName($field);
        $class = str_replace('_', '-', $property);

        $element[$property] = [
          '#type' => 'textfield',
          '#title' => $labels[$field],
          '#default_value' => isset($value[$property]) ? $value[$property] : '',
          '#required' => in_array($field, $required_fields),
          '#size' => isset($size_attributes[$field]) ? $size_attributes[$field] : 60,
          '#attributes' => [
            'class' => [$class],
            'autocomplete' => FieldHelper::getAutocompleteAttribute($field),
          ],
        ];
        if (count($line_fields) > 1) {
          $element[$property]['#group'] = $line_index;
        }
      }
    }
    // Hide the label for the second address line.
    if (isset($element['address_line2'])) {
      $element['address_line2']['#title_display'] = 'invisible';
    }
    // Hide unused fields.
    if (!empty($element['#used_fields'])) {
      $used_fields = $element['#used_fields'];
      $unused_fields = array_diff(AddressField::getAll(), $used_fields);
      foreach ($unused_fields as $field) {
        $property = FieldHelper::getPropertyName($field);
        $element[$property]['#access'] = FALSE;
      }
    }
    // Add predefined options to the created subdivision elements.
    $element = static::processSubdivisionElements($element, $value, $address_format);

    return $element;
  }

  /**
   * Processes the subdivision elements, adding predefined values where found.
   *
   * @param array $element
   *   The existing form element array.
   * @param array $value
   *   The address value, in $property_name => $value format.
   * @param \CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format
   *   The address format.
   *
   * @return array
   *   The processed form element array.
   */
  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.
    $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);
      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;
  }

  /**
   * Groups elements with the same #group so that they can be inlined.
   */
  public static function groupElements(array $element) {
    $sort = [];
    foreach (Element::getVisibleChildren($element) as $key) {
      if (isset($element[$key]['#group'])) {
        // Copy the element to the container and remove the original.
        $group_index = $element[$key]['#group'];
        $container_key = 'container' . $group_index;
        $element[$container_key][$key] = $element[$key];
        unset($element[$key]);
        // Mark the container for sorting.
        if (!in_array($container_key, $sort)) {
          $sort[] = $container_key;
        }
      }
    }
    // Sort the moved elements, so that their #weight stays respected.
    foreach ($sort as $key) {
      uasort($element[$key], [SortArray::class, 'sortByWeightProperty']);
    }

    return $element;
  }

  /**
   * Ajax callback.
   */
  public static function ajaxRefresh(array $form, FormStateInterface $form_state) {
    $country_element = $form_state->getTriggeringElement();
    $address_element = NestedArray::getValue($form, array_slice($country_element['#array_parents'], 0, -1));

    return $address_element;
  }

  /**
   * 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.
   */
  public static function clearValues(array $element, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    if (!$triggering_element) {
      return $element;
    }

    $triggering_element_name = end($triggering_element['#parents']);
    if ($triggering_element_name == 'country_code') {
      $keys = [
        'dependent_locality', 'locality', 'administrative_area',
        'postal_code', 'sorting_code',
      ];
      $input = &$form_state->getUserInput();
      foreach ($keys as $key) {
        $parents = array_merge($element['#parents'], [$key]);
        NestedArray::setValue($input, $parents, '');
        $element[$key]['#value'] = '';
      }
    }

    return $element;
  }


}