View source
<?php
namespace Drupal\physical\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\PreconfiguredFieldUiOptionsInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\physical\Measurement;
use Drupal\physical\MeasurementType;
class MeasurementItem extends FieldItemBase implements PreconfiguredFieldUiOptionsInterface {
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['number'] = DataDefinition::create('string')
->setLabel(t('Number'));
$properties['unit'] = DataDefinition::create('string')
->setLabel(t('Unit'));
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'number' => [
'description' => 'The number.',
'type' => 'numeric',
'precision' => 19,
'scale' => 6,
],
'unit' => [
'description' => 'The unit.',
'type' => 'varchar',
'length' => '255',
'default' => '',
],
],
];
}
public static function mainPropertyName() {
return NULL;
}
public function getConstraints() {
$constraint_manager = $this
->getTypedDataManager()
->getValidationConstraintManager();
$constraints = parent::getConstraints();
$constraints[] = $constraint_manager
->create('ComplexData', [
'number' => [
'Regex' => [
'pattern' => '/^[+-]?((\\d+(\\.\\d*)?)|(\\.\\d+))$/i',
],
],
]);
return $constraints;
}
public function isEmpty() {
return $this->number === NULL || $this->number === '' || empty($this->unit);
}
public function setValue($values, $notify = TRUE) {
if ($values instanceof Measurement) {
$measurement = $values;
$values = [
'number' => $measurement
->getNumber(),
'unit' => $measurement
->getUnit(),
];
}
parent::setValue($values, $notify);
}
public static function defaultStorageSettings() {
return [
'measurement_type' => MeasurementType::LENGTH,
] + parent::defaultStorageSettings();
}
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element['measurement_type'] = [
'#type' => 'radios',
'#title' => t('Measurement type'),
'#options' => MeasurementType::getLabels(),
'#default_value' => $this
->getSetting('measurement_type'),
'#required' => TRUE,
'#disabled' => $has_data,
];
return $element;
}
public static function getPreconfiguredOptions() {
$options = [];
foreach (MeasurementType::getLabels() as $type => $label) {
$options[$type] = [
'label' => $label,
'field_storage_config' => [
'settings' => [
'measurement_type' => $type,
],
],
];
}
return $options;
}
public function toMeasurement() {
$class = MeasurementType::getClass($this
->getSetting('measurement_type'));
return new $class($this->number, $this->unit);
}
}