I create a custom content entity type.
I want one field for the event time.
Since there is no time field, but a dataTime_type, I create a plugin for a custom field :
FieldType : TimeItem.php
/**
* Plugin implementation of the 'time' field type.
*
* @FieldType(
* id = "time",
* label = @Translation("Time Field"),
* description = @Translation("Permet la creation d'un champ de type time"),
* default_widget = "time_widget",
* default_formatter = "time_formatter"
* )
*/
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'value' => array(
'description' => 'The time value.',
'type' => 'int',
'length' => 6,
),
),
);
}
I try to change type to time (for mysql) but mysql error return me a null for the type. So I use int for store time in seconde.
FieldWidget : TimeWIdget.php
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';
$element += array(
'#type' => 'time', //HTML5 input
'#default_value' => $value,
'#size' => 4,
'#element_validate' => array(
array($this, 'validate'),
),
);
return $element;
}
My entity :
$fields['heure_evenement'] = BaseFieldDefinition::create('time')
->setLabel(t('test'))
->setDescription(t('test'))
->setRequired(TRUE)
->setDefaultValue('')
->setDisplayOptions('view', array(
'label' => 'above',
'type' => 'string',
'weight' => 3,
))
->setDisplayOptions('form', array(
'weight' => 3,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
All is working except one thing, the HTML5 input type time
Drupal know some input in html5 but not all... type tel, email, number, range, color, date, datetime is ok but not the type time alone.
So I was hoping get it with a custom plugin, but no...
Edit 1
The only way I have found is to create 2 select for this type :
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';
//heure
for($i=0;$i<=24;$i++){
$hour[]=$i;
}
//minutes
for($i=0;$i<=59;$i++){
$minutes[]=$i;
}
$element += array('hour'=>array(
'#title'=>t('Hour'),
'#type' => 'select',
'#options'=>$hour,
'#default_value' => $value,
'#element_validate' => array(
array($this, 'validate'),
),
)
);
$element += array('minutes'=>array(
'#title'=>t('Minutes'),
'#type' => 'select',
'#options'=>$minutes,
'#default_value' => $value,
'#element_validate' => array(
array($this, 'validate'),
),
)
);
return $element;
}
Any idea about this?