TimestampDatetimeOptionalWidget.php in farmOS 2.x
File
modules/core/field/src/Plugin/Field/FieldWidget/TimestampDatetimeOptionalWidget.php
View source
<?php
namespace Drupal\farm_field\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;
class TimestampDatetimeOptionalWidget 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.', [
'%format' => Datetime::formatExample($date_format . ' ' . $time_format),
]);
return $element;
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$item) {
if (isset($item['value']) && $item['value'] instanceof DrupalDateTime) {
$date = $item['value'];
}
elseif (isset($item['value']['object']) && $item['value']['object'] instanceof DrupalDateTime) {
$date = $item['value']['object'];
}
$item['value'] = !empty($date) ? $date
->getTimestamp() : NULL;
}
return $values;
}
}