TelephoneItem.php 2.12 KB
Newer Older
1 2
<?php

3
namespace Drupal\telephone\Plugin\Field\FieldType;
4

5
use Drupal\Core\Field\FieldDefinitionInterface;
6
use Drupal\Core\Field\FieldItemBase;
7
use Drupal\Core\Field\FieldStorageDefinitionInterface;
8
use Drupal\Core\TypedData\DataDefinition;
9 10 11 12 13 14 15 16

/**
 * Plugin implementation of the 'telephone' field type.
 *
 * @FieldType(
 *   id = "telephone",
 *   label = @Translation("Telephone number"),
 *   description = @Translation("This field stores a telephone number in the database."),
17
 *   category = @Translation("Number"),
18
 *   default_widget = "telephone_default",
19
 *   default_formatter = "basic_string"
20 21
 * )
 */
22
class TelephoneItem extends FieldItemBase {
23 24 25 26

  /**
   * {@inheritdoc}
   */
27
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
28 29 30
    return [
      'columns' => [
        'value' => [
31 32
          'type' => 'varchar',
          'length' => 256,
33 34 35
        ],
      ],
    ];
36 37 38 39 40
  }

  /**
   * {@inheritdoc}
   */
41
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
42
    $properties['value'] = DataDefinition::create('string')
43 44
      ->setLabel(t('Telephone number'))
      ->setRequired(TRUE);
45 46

    return $properties;
47 48 49 50 51 52 53 54 55 56 57 58 59 60
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('value')->getValue();
    return $value === NULL || $value === '';
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
61
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
62 63 64
    $constraints = parent::getConstraints();

    $max_length = 256;
65 66 67
    $constraints[] = $constraint_manager->create('ComplexData', [
      'value' => [
        'Length' => [
68
          'max' => $max_length,
69
          'maxMessage' => t('%name: the telephone number may not be longer than @max characters.', ['%name' => $this->getFieldDefinition()->getLabel(), '@max' => $max_length]),
70
        ],
71 72
      ],
    ]);
73 74 75 76

    return $constraints;
  }

77 78 79 80
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
81
    $values['value'] = rand(pow(10, 8), pow(10, 9) - 1);
82 83 84
    return $values;
  }

85
}