View source
<?php
namespace Drupal\physical\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\physical\Length;
class DimensionsItem extends FieldItemBase {
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'length' => [
'description' => 'The length.',
'type' => 'numeric',
'default' => 0,
'precision' => 19,
'scale' => 6,
],
'width' => [
'description' => 'The width.',
'type' => 'numeric',
'size' => 'normal',
'precision' => 19,
'scale' => 6,
],
'height' => [
'description' => 'The height.',
'type' => 'numeric',
'size' => 'normal',
'precision' => 19,
'scale' => 6,
],
'unit' => [
'description' => 'The unit.',
'type' => 'varchar',
'length' => '255',
'default' => '',
],
],
];
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['length'] = DataDefinition::create('string')
->setLabel(t('Length'));
$properties['width'] = DataDefinition::create('string')
->setLabel(t('Width'));
$properties['height'] = DataDefinition::create('string')
->setLabel(t('Height'));
$properties['unit'] = DataDefinition::create('string')
->setLabel(t('Unit'));
return $properties;
}
public static function mainPropertyName() {
return NULL;
}
public function getConstraints() {
$constraint_manager = $this
->getTypedDataManager()
->getValidationConstraintManager();
$constraints = parent::getConstraints();
$constraints[] = $constraint_manager
->create('Dimensions', []);
return $constraints;
}
public function isEmpty() {
if (empty($this->unit)) {
return TRUE;
}
if ($this
->checkEmpty($this->length) && $this
->checkEmpty($this->width) && $this
->checkEmpty($this->height)) {
return TRUE;
}
return FALSE;
}
protected function checkEmpty($value) {
return is_null($value) || $value === '';
}
public function getLength() {
return new Length($this->length, $this->unit);
}
public function getWidth() {
return new Length($this->width, $this->unit);
}
public function getHeight() {
return new Length($this->height, $this->unit);
}
}