Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / telephone / src / Plugin / Field / FieldType / TelephoneItem.php
1 <?php
2
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  * Plugin implementation of the 'telephone' field type.
12  *
13  * @FieldType(
14  *   id = "telephone",
15  *   label = @Translation("Telephone number"),
16  *   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    * {@inheritdoc}
26    */
27   public static function schema(FieldStorageDefinitionInterface $field_definition) {
28     return [
29       'columns' => [
30         'value' => [
31           'type' => 'varchar',
32           'length' => 256,
33         ],
34       ],
35     ];
36   }
37
38   /**
39    * {@inheritdoc}
40    */
41   public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
42     $properties['value'] = DataDefinition::create('string')
43       ->setLabel(t('Telephone number'))
44       ->setRequired(TRUE);
45
46     return $properties;
47   }
48
49   /**
50    * {@inheritdoc}
51    */
52   public function isEmpty() {
53     $value = $this->get('value')->getValue();
54     return $value === NULL || $value === '';
55   }
56
57   /**
58    * {@inheritdoc}
59    */
60   public function getConstraints() {
61     $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
62     $constraints = parent::getConstraints();
63
64     $max_length = 256;
65     $constraints[] = $constraint_manager->create('ComplexData', [
66       'value' => [
67         '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     return $constraints;
75   }
76
77   /**
78    * {@inheritdoc}
79    */
80   public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
81     $values['value'] = rand(pow(10, 8), pow(10, 9) - 1);
82     return $values;
83   }
84
85 }