View source
<?php
namespace Drupal\yamlform\Element;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Form\FormStateInterface;
class YamlFormTime extends FormElement {
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#theme' => 'input__time',
'#process' => [
[
$class,
'processYamlFormTime',
],
],
'#pre_render' => [
[
$class,
'preRenderYamlFormTime',
],
],
'#element_validate' => [
[
$class,
'validateYamlFormTime',
],
],
'#theme_wrappers' => [
'form_element',
],
'#time_format' => 'H:i',
'#size' => 10,
'#maxlength' => 10,
];
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if ($input === FALSE) {
if (!empty($element['#default_value'])) {
$element['#default_value'] = date('H:i', strtotime($element['#default_value']));
return $element['#default_value'];
}
}
return $input;
}
public static function processYamlFormTime(&$element, FormStateInterface $form_state, &$complete_form) {
if (!empty($element['#time_format'])) {
$element['#attached']['library'][] = 'yamlform/yamlform.element.time';
$element['#attributes']['data-yamlform-time-format'] = [
$element['#time_format'],
];
}
return $element;
}
public static function validateYamlFormTime(&$element, FormStateInterface $form_state, &$complete_form) {
$has_access = !isset($element['#access']) || $element['#access'] === TRUE;
$value = $element['#value'];
if ($value === '') {
return;
}
$time = strtotime($value);
if ($time === FALSE) {
if ($has_access) {
if (isset($element['#title'])) {
$form_state
->setError($element, t('%name must be a valid time.', [
'%name' => $element['#title'],
]));
}
else {
$form_state
->setError($element);
}
}
return;
}
$name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
$time_format = !empty($element['#time_format']) ? $element['#time_format'] : DateFormat::load('html_time')
->getPattern();
if ($has_access && isset($element['#min'])) {
$min = strtotime($element['#min']);
if ($time < $min) {
$form_state
->setError($element, t('%name must be on or after %min.', [
'%name' => $name,
'%min' => date($time_format, $min),
]));
}
}
if ($has_access && isset($element['#max'])) {
$max = strtotime($element['#max']);
if ($time > $max) {
$form_state
->setError($element, t('%name must be on or before %max.', [
'%name' => $name,
'%max' => date($time_format, $max),
]));
}
}
$form_state
->setValueForElement($element, date('H:i:s', $time));
}
public static function preRenderYamlFormTime($element) {
$element['#attributes']['type'] = 'time';
Element::setAttributes($element, [
'id',
'name',
'type',
'value',
'size',
'min',
'max',
'step',
]);
static::setAttributes($element, [
'form-time',
]);
return $element;
}
}