EmailItem.php 2.1 KB
Newer Older
1 2
<?php

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

5 6
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
7
use Drupal\Core\Field\FieldStorageDefinitionInterface;
8
use Drupal\Core\Field\FieldItemBase;
9
use Drupal\Core\Render\Element\Email;
10
use Drupal\Core\TypedData\DataDefinition;
11 12

/**
13
 * Defines the 'email' field type.
14
 *
15 16
 * @FieldType(
 *   id = "email",
17 18
 *   label = @Translation("Email"),
 *   description = @Translation("An entity field containing an email value."),
19
 *   default_widget = "email_default",
20
 *   default_formatter = "basic_string"
21
 * )
22
 */
23
class EmailItem extends FieldItemBase {
24 25

  /**
26
   * {@inheritdoc}
27
   */
28
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
29
    $properties['value'] = DataDefinition::create('email')
30
      ->setLabel(t('Email'))
31
      ->setRequired(TRUE);
32

33
    return $properties;
34
  }
35

36 37 38
  /**
   * {@inheritdoc}
   */
39
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
40 41 42
    return [
      'columns' => [
        'value' => [
43
          'type' => 'varchar',
44
          'length' => Email::EMAIL_MAX_LENGTH,
45 46 47
        ],
      ],
    ];
48 49 50 51 52 53 54 55 56
  }

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

57 58 59
    $constraints[] = $constraint_manager->create('ComplexData', [
      'value' => [
        'Length' => [
60
          'max' => Email::EMAIL_MAX_LENGTH,
61
          'maxMessage' => t('%name: the email address can not be longer than @max characters.', ['%name' => $this->getFieldDefinition()->getLabel(), '@max' => Email::EMAIL_MAX_LENGTH]),
62
        ],
63 64
      ],
    ]);
65 66 67

    return $constraints;
  }
68

69 70 71 72 73 74 75 76 77
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $values['value'] = $random->name() . '@example.com';
    return $values;
  }

78 79 80 81
  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
82
    return $this->value === NULL || $this->value === '';
83
  }
84

85
}