TelephoneItem.php

Same filename and directory in other branches
  1. 9 core/modules/telephone/src/Plugin/Field/FieldType/TelephoneItem.php
  2. 8.9.x core/modules/telephone/src/Plugin/Field/FieldType/TelephoneItem.php
  3. 11.x core/modules/telephone/src/Plugin/Field/FieldType/TelephoneItem.php

Namespace

Drupal\telephone\Plugin\Field\FieldType

File

core/modules/telephone/src/Plugin/Field/FieldType/TelephoneItem.php

View source
<?php

namespace Drupal\telephone\Plugin\Field\FieldType;

use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'telephone' field type.
 */
class TelephoneItem extends FieldItemBase {
  
  /**
   * The maximum length for a telephone value.
   */
  const MAX_LENGTH = 256;
  
  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'value' => [
          'type' => 'varchar',
          'length' => self::MAX_LENGTH,
        ],
      ],
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('string')->setLabel(new TranslatableMarkup('Telephone number'))
      ->setRequired(TRUE);
    return $properties;
  }
  
  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('value')
      ->getValue();
    return $value === NULL || $value === '';
  }
  
  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();
    $constraints[] = $constraint_manager->create('ComplexData', [
      'value' => [
        'Length' => [
          'max' => self::MAX_LENGTH,
          'maxMessage' => $this->t('%name: the telephone number may not be longer than @max characters.', [
            '%name' => $this->getFieldDefinition()
              ->getLabel(),
            '@max' => self::MAX_LENGTH,
          ]),
        ],
      ],
    ]);
    return $constraints;
  }
  
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $values['value'] = rand(pow(10, 8), pow(10, 9) - 1);
    return $values;
  }

}

Classes

Title Deprecated Summary
TelephoneItem Plugin implementation of the 'telephone' field type.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.