Newer
Older
Alex Pott
committed
<?php
Alex Pott
committed
namespace Drupal\telephone\Plugin\Field\FieldType;
Alex Pott
committed
use Drupal\Core\Field\FieldDefinitionInterface;
Alex Pott
committed
use Drupal\Core\Field\FieldItemBase;
Alex Pott
committed
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
Alex Pott
committed
/**
* 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."),
* category = @Translation("Number"),
Alex Pott
committed
* default_widget = "telephone_default",
catch
committed
* default_formatter = "basic_string"
Alex Pott
committed
* )
*/
Alex Pott
committed
class TelephoneItem extends FieldItemBase {
Alex Pott
committed
/**
* {@inheritdoc}
*/
Alex Pott
committed
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
Alex Pott
committed
'type' => 'varchar',
'length' => 256,
],
],
];
Alex Pott
committed
}
/**
* {@inheritdoc}
*/
Alex Pott
committed
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(t('Telephone number'))
->setRequired(TRUE);
return $properties;
Alex Pott
committed
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$value = $this->get('value')->getValue();
return $value === NULL || $value === '';
}
/**
* {@inheritdoc}
*/
public function getConstraints() {
$constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
Alex Pott
committed
$constraints = parent::getConstraints();
$max_length = 256;
$constraints[] = $constraint_manager->create('ComplexData', [
'value' => [
'Length' => [
Alex Pott
committed
'max' => $max_length,
'maxMessage' => t('%name: the telephone number may not be longer than @max characters.', ['%name' => $this->getFieldDefinition()->getLabel(), '@max' => $max_length]),
]
],
]);
Alex Pott
committed
return $constraints;
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
Alex Pott
committed
$values['value'] = rand(pow(10, 8), pow(10, 9) - 1);
return $values;
}