DatexTimestampDatetimeNoDefaultWidget.php in Datex 8
File
src/Plugin/Field/FieldWidget/DatexTimestampDatetimeNoDefaultWidget.php
View source
<?php
namespace Drupal\datex\Plugin\Field\FieldWidget;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Datetime\Element\Datetime;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Datetime\Plugin\Field\FieldWidget\TimestampDatetimeWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\datex\Element\DatexDateTime;
use Drupal\scheduler\Plugin\Field\FieldWidget\TimestampDatetimeNoDefaultWidget;
class DatexTimestampDatetimeNoDefaultWidget extends TimestampDatetimeWidget {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$date_format = DateFormat::load('html_date')
->getPattern();
$time_format = DateFormat::load('html_time')
->getPattern();
$element['value']['#description'] = $this
->t('Format: %format. Leave blank for no date.', [
'%format' => Datetime::formatExample($date_format . ' ' . $time_format),
]);
$element['value']['#value_callback'] = [
$this,
'valueCallback',
];
return $element;
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if ($input !== FALSE) {
$date_input = $element['#date_date_element'] != 'none' && !empty($input['date']) ? $input['date'] : '';
$time_input = $element['#date_time_element'] != 'none' && !empty($input['time']) ? $input['time'] : '';
$config = \Drupal::config('scheduler.settings');
if (!empty($date_input) && empty($time_input) && $config
->get('allow_date_only')) {
$input['time'] = $config
->get('default_time');
}
}
return DatexDateTime::valueCallback($element, $input, $form_state);
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$item) {
$date = NULL;
$timezone = drupal_get_user_timezone();
if (isset($item['value']) && $item['value'] instanceof DrupalDateTime) {
$date = $item['value'];
$calendar = datex_factory($timezone, 'en');
if ($calendar && $date
->format('Y') < 1600) {
$ok = $calendar
->parse($date
->format('Y m d H i s'), 'Y m d H i s');
if ($ok) {
$date = DrupalDateTime::createFromTimestamp($calendar
->getTimestamp(), $timezone);
}
}
}
elseif (isset($item['value']['object']) && $item['value']['object'] instanceof DrupalDateTime) {
$date = $item['value']['object'];
}
$item['value'] = $date ? $date
->getTimestamp() : NULL;
}
return $values;
}
}