datetime_extras-8.x-1.x-dev/src/Plugin/Field/FieldType/TimeOnlyField.php
src/Plugin/Field/FieldType/TimeOnlyField.php
<?php
namespace Drupal\datetime_extras\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
/**
* Plugin implementation of the 'time_only_field' field type.
*
* @FieldType(
* id = "time_only_field",
* label = @Translation("Time only field"),
* description = @Translation("Allows to store only time."),
* default_widget = "time_only_field_default",
* default_formatter = "time_only_field_default",
* list_class = "\Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList"
* )
*/
class TimeOnlyField extends DateTimeItem {
/**
* Value for the 'datetime_type' setting: store a time.
*/
const DATETIME_TYPE_TIME = 'time';
/**
* {@inheritdoc}
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element = [];
$element['datetime_type'] = [
'#type' => 'select',
'#title' => t('Date type'),
'#description' => t('Choose the type of date to create.'),
'#default_value' => $this->getSetting('datetime_type'),
'#options' => [
static::DATETIME_TYPE_TIME => t('Time only'),
],
'#disabled' => $has_data,
];
return $element;
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
// Just pick a date in the past year.
$timestamp = \Drupal::time()->getRequestTime() - mt_rand(0, 86400 * 365);
$values['value'] = gmdate(self::DATETIME_STORAGE_FORMAT, $timestamp);
return $values;
}
}
