CountryItem.php 2.07 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
<?php

namespace Drupal\address\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;

/**
 * Plugin implementation of the 'address_country' field type.
 *
 * @FieldType(
 *   id = "address_country",
 *   label = @Translation("Country"),
 *   description = @Translation("An entity field containing a country"),
 *   category = @Translation("Address"),
 *   default_widget = "address_country_default",
 *   default_formatter = "address_country_default"
 * )
 */
class CountryItem extends FieldItemBase {

  use AvailableCountriesTrait;

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
bojanz's avatar
bojanz committed
30
    return [
31 32 33 34 35 36 37 38 39 40
      'columns' => [
        'value' => [
          'type' => 'char',
          'length' => 2,
          'not null' => FALSE,
        ],
      ],
      'indexes' => [
        'value' => ['value'],
      ],
bojanz's avatar
bojanz committed
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
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(t('Country'));
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return self::defaultCountrySettings();
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    return $this->countrySettingsForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    return empty($this->value);
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();
79
    $constraint_manager = $this->getTypedDataManager()->getValidationConstraintManager();
80 81 82 83 84 85 86 87 88 89 90 91
    $constraints[] = $constraint_manager->create('ComplexData', [
      'value' => [
        'Country' => [
          'availableCountries' => $this->getAvailableCountries(),
        ],
      ],
    ]);

    return $constraints;
  }

}