DurationField.php in Duration Field 3.0.x
File
src/Plugin/Field/FieldType/DurationField.php
View source
<?php
namespace Drupal\duration_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\duration_field\Plugin\DataType\Iso8601StringInterface;
class DurationField extends FieldItemBase implements FieldItemInterface {
public static function defaultFieldSettings() {
return [
'granularity' => 'y:m:d:h:i:s',
] + parent::defaultFieldSettings();
}
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element['granularity'] = [
'#type' => 'granularity',
'#title' => $this
->t('Granularity'),
'#default_value' => $this
->getSetting('granularity'),
];
return $element;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'duration' => [
'type' => 'varchar',
'length' => 255,
],
'seconds' => [
'type' => 'int',
'size' => 'big',
],
],
];
}
public function isEmpty() {
$value = $this
->get('duration')
->getValue();
return $value == Iso8601StringInterface::EMPTY_DURATION || is_null($value) || $value === '';
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['seconds'] = DataDefinition::create('integer')
->setLabel(t('Seconds'))
->setDescription(t('The number of seconds the duration represents'));
$properties['duration'] = DataDefinition::create('php_date_interval')
->setLabel('Duration')
->setDescription(t('The PHP DateInterval object'));
return $properties;
}
}