AddressItem.php 12.1 KB
Newer Older
bojanz's avatar
bojanz committed
1 2 3 4
<?php

namespace Drupal\address\Plugin\Field\FieldType;

5
use CommerceGuys\Addressing\AddressFormat\AddressField;
6 7
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
use CommerceGuys\Addressing\AddressFormat\FieldOverrides;
8
use Drupal\address\AddressInterface;
9
use Drupal\address\LabelHelper;
bojanz's avatar
bojanz committed
10 11
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
bojanz's avatar
bojanz committed
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Language\LanguageInterface;
bojanz's avatar
bojanz committed
14 15 16 17 18 19 20 21 22
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'address' field type.
 *
 * @FieldType(
 *   id = "address",
 *   label = @Translation("Address"),
 *   description = @Translation("An entity field containing a postal address"),
23
 *   category = @Translation("Address"),
bojanz's avatar
bojanz committed
24
 *   default_widget = "address_default",
25 26
 *   default_formatter = "address_default",
 *   list_class = "\Drupal\address\Plugin\Field\FieldType\AddressFieldItemList"
bojanz's avatar
bojanz committed
27 28 29 30
 * )
 */
class AddressItem extends FieldItemBase implements AddressInterface {

31
  use AvailableCountriesTrait;
32

bojanz's avatar
bojanz committed
33 34 35
  /**
   * {@inheritdoc}
   */
36
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
37 38
    return [
      'columns' => [
39 40 41 42
        'langcode' => [
          'type' => 'varchar',
          'length' => 32,
        ],
43
        'country_code' => [
bojanz's avatar
bojanz committed
44 45
          'type' => 'varchar',
          'length' => 2,
46 47
        ],
        'administrative_area' => [
bojanz's avatar
bojanz committed
48 49
          'type' => 'varchar',
          'length' => 255,
50 51
        ],
        'locality' => [
bojanz's avatar
bojanz committed
52 53
          'type' => 'varchar',
          'length' => 255,
54 55
        ],
        'dependent_locality' => [
bojanz's avatar
bojanz committed
56 57
          'type' => 'varchar',
          'length' => 255,
58 59
        ],
        'postal_code' => [
bojanz's avatar
bojanz committed
60 61
          'type' => 'varchar',
          'length' => 255,
62 63
        ],
        'sorting_code' => [
bojanz's avatar
bojanz committed
64 65
          'type' => 'varchar',
          'length' => 255,
66 67
        ],
        'address_line1' => [
bojanz's avatar
bojanz committed
68 69
          'type' => 'varchar',
          'length' => 255,
70 71
        ],
        'address_line2' => [
bojanz's avatar
bojanz committed
72 73
          'type' => 'varchar',
          'length' => 255,
74 75
        ],
        'organization' => [
bojanz's avatar
bojanz committed
76 77
          'type' => 'varchar',
          'length' => 255,
78
        ],
79 80 81 82 83 84 85 86 87
        'given_name' => [
          'type' => 'varchar',
          'length' => 255,
        ],
        'additional_name' => [
          'type' => 'varchar',
          'length' => 255,
        ],
        'family_name' => [
bojanz's avatar
bojanz committed
88 89
          'type' => 'varchar',
          'length' => 255,
90 91 92
        ],
      ],
    ];
bojanz's avatar
bojanz committed
93 94
  }

95 96 97 98 99 100 101
  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    return NULL;
  }

bojanz's avatar
bojanz committed
102 103 104
  /**
   * {@inheritdoc}
   */
105
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
106
    $properties = [];
107
    $properties['langcode'] = DataDefinition::create('string')
108
      ->setLabel(t('The language code'));
bojanz's avatar
bojanz committed
109
    $properties['country_code'] = DataDefinition::create('string')
110
      ->setLabel(t('The two-letter country code'));
bojanz's avatar
bojanz committed
111
    $properties['administrative_area'] = DataDefinition::create('string')
112
      ->setLabel(t('The top-level administrative subdivision of the country'));
bojanz's avatar
bojanz committed
113
    $properties['locality'] = DataDefinition::create('string')
114
      ->setLabel(t('The locality (i.e. city)'));
bojanz's avatar
bojanz committed
115
    $properties['dependent_locality'] = DataDefinition::create('string')
116
      ->setLabel(t('The dependent locality (i.e. neighbourhood)'));
bojanz's avatar
bojanz committed
117
    $properties['postal_code'] = DataDefinition::create('string')
118
      ->setLabel(t('The postal code'));
bojanz's avatar
bojanz committed
119
    $properties['sorting_code'] = DataDefinition::create('string')
120
      ->setLabel(t('The sorting code'));
bojanz's avatar
bojanz committed
121
    $properties['address_line1'] = DataDefinition::create('string')
122
      ->setLabel(t('The first line of the address block'));
bojanz's avatar
bojanz committed
123
    $properties['address_line2'] = DataDefinition::create('string')
124
      ->setLabel(t('The second line of the address block'));
bojanz's avatar
bojanz committed
125 126
    $properties['organization'] = DataDefinition::create('string')
      ->setLabel(t('The organization'));
127
    $properties['given_name'] = DataDefinition::create('string')
128
      ->setLabel(t('The given name'));
129
    $properties['additional_name'] = DataDefinition::create('string')
130
      ->setLabel(t('The additional name'));
131
    $properties['family_name'] = DataDefinition::create('string')
132
      ->setLabel(t('The family name'));
bojanz's avatar
bojanz committed
133 134 135 136

    return $properties;
  }

137 138 139 140
  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
141
    return self::defaultCountrySettings() + [
142
      'langcode_override' => '',
143 144 145
      'field_overrides' => [],
      // Replaced by field_overrides.
      'fields' => [],
146
    ];
147 148 149 150 151 152
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
153
    $languages = \Drupal::languageManager()->getLanguages(LanguageInterface::STATE_ALL);
154
    $language_options = [];
155 156 157
    foreach ($languages as $langcode => $language) {
      // Only list real languages (English, French, but not "Not specified").
      if (!$language->isLocked()) {
158
        $language_options[$langcode] = $language->getName();
159 160 161
      }
    }

162
    $element = $this->countrySettingsForm($form, $form_state);
163 164 165 166
    $element['langcode_override'] = [
      '#type' => 'select',
      '#title' => $this->t('Language override'),
      '#description' => $this->t('Ensures entered addresses are always formatted in the same language.'),
167
      '#options' => $language_options,
168 169 170 171
      '#default_value' => $this->getSetting('langcode_override'),
      '#empty_option' => $this->t('- No override -'),
      '#access' => \Drupal::languageManager()->isMultilingual(),
    ];
172

173 174 175
    $element['field_overrides_title'] = [
      '#type' => 'item',
      '#title' => $this->t('Field overrides'),
176
      '#description' => $this->t('Use field overrides to override the country-specific address format, forcing specific properties to always be hidden, optional, or required.'),
177 178 179 180
    ];
    $element['field_overrides'] = [
      '#type' => 'table',
      '#header' => [
181
        $this->t('Property'),
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        $this->t('Override'),
      ],
      '#element_validate' => [[get_class($this), 'fieldOverridesValidate']],
    ];
    $field_overrides = $this->getFieldOverrides();
    foreach (LabelHelper::getGenericFieldLabels() as $field_name => $label) {
      $override = isset($field_overrides[$field_name]) ? $field_overrides[$field_name] : '';

      $element['field_overrides'][$field_name] = [
        'field_label' => [
          '#type' => 'markup',
          '#markup' => $label,
        ],
        'override' => [
          '#type' => 'select',
          '#options' => [
198 199 200
            FieldOverride::HIDDEN => $this->t('Hidden'),
            FieldOverride::OPTIONAL => $this->t('Optional'),
            FieldOverride::REQUIRED => $this->t('Required'),
201 202 203 204 205 206 207
          ],
          '#default_value' => $override,
          '#empty_option' => $this->t('- No override -'),
        ],
      ];
    }

208 209 210
    return $element;
  }

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
  /**
   * Form element validation handler: Removes empty field overrides.
   *
   * @param array $element
   *   The field overrides form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state of the entire form.
   */
  public static function fieldOverridesValidate(array $element, FormStateInterface $form_state) {
    $overrides = $form_state->getValue($element['#parents']);
    $overrides = array_filter($overrides, function ($data) {
      return !empty($data['override']);
    });
    $form_state->setValue($element['#parents'], $overrides);
  }

  /**
   * Gets the field overrides for the current field.
   *
   * @return array
   *   FieldOverride constants keyed by AddressField constants.
   */
  public function getFieldOverrides() {
    $field_overrides = [];
    if ($fields = $this->getSetting('fields')) {
      $unused_fields = array_diff(AddressField::getAll(), $fields);
      foreach ($unused_fields as $field) {
        $field_overrides[$field] = FieldOverride::HIDDEN;
      }
    }
241 242
    elseif ($overrides = $this->getSetting('field_overrides')) {
      foreach ($overrides as $field => $data) {
243 244 245 246 247 248 249
        $field_overrides[$field] = $data['override'];
      }
    }

    return $field_overrides;
  }

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  /**
   * Initializes and returns the langcode property for the current field.
   *
   * Some countries use separate address formats for the local language VS
   * other languages. For example, China uses major-to-minor ordering
   * when the address is entered in Chinese, and minor-to-major when the
   * address is entered in other languages.
   * This means that the address must remember which language it was
   * entered in, to ensure consistent formatting later on.
   *
   * - For translatable entities this information comes from the field langcode.
   * - Non-translatable entities have no way to provide this information, since
   *   the field langcode never changes. In this case the field must store
   *   the interface language at the time of address creation.
   * - It is also possible to override the used language via field settings,
   *   in case the language is always known (e.g. a field storing the "english
   *   address" on a chinese article).
   *
268
   * The langcode property is interpreted by getLocale(), and in case it's NULL,
269 270 271 272 273 274 275 276
   * the field langcode is returned instead (indicating a non-multilingual site
   * or a translatable parent entity).
   *
   * @return string|null
   *   The langcode, or NULL if the field langcode should be used instead.
   */
  public function initializeLangcode() {
    $this->langcode = NULL;
277 278
    $language_manager = \Drupal::languageManager();
    if (!$language_manager->isMultilingual()) {
279 280 281 282 283 284 285
      return;
    }

    if ($override = $this->getSetting('langcode_override')) {
      $this->langcode = $override;
    }
    elseif (!$this->getEntity()->isTranslatable()) {
286
      // The getCurrentLanguage fallback is a workaround for core bug #2684873.
287
      $language = $language_manager->getConfigOverrideLanguage() ?: $language_manager->getCurrentLanguage();
288
      $this->langcode = $language->getId();
289 290 291 292 293
    }

    return $this->langcode;
  }

bojanz's avatar
bojanz committed
294 295 296 297 298
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();
299
    $constraint_manager = $this->getTypedDataManager()->getValidationConstraintManager();
300
    $field_overrides = new FieldOverrides($this->getFieldOverrides());
301 302 303 304 305 306 307
    $constraints[] = $constraint_manager->create('ComplexData', [
      'country_code' => [
        'Country' => [
          'availableCountries' => $this->getAvailableCountries(),
        ],
      ],
    ]);
308
    $constraints[] = $constraint_manager->create('AddressFormat', ['fieldOverrides' => $field_overrides]);
bojanz's avatar
bojanz committed
309 310 311 312

    return $constraints;
  }

bojanz's avatar
bojanz committed
313 314 315 316 317 318 319 320 321 322 323 324
  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->country_code;
    return $value === NULL || $value === '';
  }

  /**
   * {@inheritdoc}
   */
  public function getLocale() {
325 326 327 328 329 330 331 332
    $langcode = $this->langcode;
    if (!$langcode) {
      // If no langcode was stored, fallback to the field langcode.
      // Documented in initializeLangcode().
      $langcode = $this->getLangcode();
    }

    return $langcode;
bojanz's avatar
bojanz committed
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
  }

  /**
   * {@inheritdoc}
   */
  public function getCountryCode() {
    return $this->country_code;
  }

  /**
   * {@inheritdoc}
   */
  public function getAdministrativeArea() {
    return $this->administrative_area;
  }

  /**
   * {@inheritdoc}
   */
  public function getLocality() {
    return $this->locality;
  }

  /**
   * {@inheritdoc}
   */
  public function getDependentLocality() {
    return $this->dependent_locality;
  }

  /**
   * {@inheritdoc}
   */
  public function getPostalCode() {
    return $this->postal_code;
  }

  /**
   * {@inheritdoc}
   */
  public function getSortingCode() {
    return $this->sorting_code;
  }

  /**
   * {@inheritdoc}
   */
  public function getAddressLine1() {
    return $this->address_line1;
  }

  /**
   * {@inheritdoc}
   */
  public function getAddressLine2() {
    return $this->address_line2;
  }

  /**
   * {@inheritdoc}
   */
  public function getOrganization() {
    return $this->organization;
  }

  /**
   * {@inheritdoc}
   */
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
  public function getGivenName() {
    return $this->given_name;
  }

  /**
   * {@inheritdoc}
   */
  public function getAdditionalName() {
    return $this->additional_name;
  }

  /**
   * {@inheritdoc}
   */
  public function getFamilyName() {
    return $this->family_name;
bojanz's avatar
bojanz committed
417 418 419
  }

}