3 namespace Drupal\datetime\Plugin\Field\FieldWidget;
5 use Drupal\Core\Entity\EntityStorageInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\FieldDefinitionInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
10 use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
11 use Symfony\Component\DependencyInjection\ContainerInterface;
14 * Plugin implementation of the 'datetime_default' widget.
17 * id = "datetime_default",
18 * label = @Translation("Date and time"),
24 class DateTimeDefaultWidget extends DateTimeWidgetBase implements ContainerFactoryPluginInterface {
27 * The date format storage.
29 * @var \Drupal\Core\Entity\EntityStorageInterface
31 protected $dateStorage;
36 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityStorageInterface $date_storage) {
37 parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
39 $this->dateStorage = $date_storage;
45 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
49 $configuration['field_definition'],
50 $configuration['settings'],
51 $configuration['third_party_settings'],
52 $container->get('entity.manager')->getStorage('date_format')
59 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
60 $element = parent::formElement($items, $delta, $element, $form, $form_state);
62 // If the field is date-only, make sure the title is displayed. Otherwise,
63 // wrap everything in a fieldset, and the title will be shown in the legend.
64 if ($this->getFieldSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
65 $element['value']['#title'] = $this->fieldDefinition->getLabel();
66 $element['value']['#description'] = $this->fieldDefinition->getDescription();
69 $element['#theme_wrappers'][] = 'fieldset';
72 // Identify the type of date and time elements to use.
73 switch ($this->getFieldSetting('datetime_type')) {
74 case DateTimeItem::DATETIME_TYPE_DATE:
77 $date_format = $this->dateStorage->load('html_date')->getPattern();
84 $date_format = $this->dateStorage->load('html_date')->getPattern();
85 $time_format = $this->dateStorage->load('html_time')->getPattern();
89 $element['value'] += [
90 '#date_date_format' => $date_format,
91 '#date_date_element' => $date_type,
92 '#date_date_callbacks' => [],
93 '#date_time_format' => $time_format,
94 '#date_time_element' => $time_type,
95 '#date_time_callbacks' => [],