8

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?

2
12
+50

The form element property #type refers to an element type, not a HTML element. It is okay to define your own element types (or theme types), and you can provide your own markup for it. This can be done by implementing a RenderElement plugin.

Update:

You can also use the datetime render element and disable the date portion.

$element['#date_date_element'] = 'none';

Update 2:

The comment form has an example of a render array that uses the datetime type. So given that as a guideline,

  $form['time_without_date'] = array(
    '#type' => 'datetime',
    '#title' => $this->t('Time without date'),
    // HTML 5 time element format can be H:i
    '#default_value' => DrupalDateTime::createFromFormat('Y-m-d H:i:s', '1970-01-01 20:00', 'UTC'),
    '#size' => 20,
    '#date_date_element' => 'none',
    // This sets html 5 time element use explicitly, probably not necessary.
    '#date_time_element' => 'time',
  );
8
  • 2
    I also remembered something about the datetime element. You should be able to set none for the date portion and get back only the time portion. – mradcliffe Jul 10 '16 at 15:03
  • @mradcliffe Could you provide detailed instructions for this newbie? If I'm able to get it working, I would not hesitate to give you the bounty! Thanks! – Chris Happy Jan 30 '17 at 5:04
  • Is there something particular that you are stuck on? It's probably hard to post code in a comment, but I would make sure that in your form array the appropriate element properties (keys with '#') are set. I'll update the answer with some examples from api.drupal.org in a bit. – mradcliffe Jan 30 '17 at 14:43
  • 1
    He created another question here: drupal.stackexchange.com/questions/227029/…, as his question was more specific to field widget rather than form API elements. – mradcliffe Feb 1 '17 at 14:42
  • 1
    @AdrianCidAlmaguer Yes, I have shared the code here. I'll consider transforming it to Github. Hope it helps! – Chris Happy Feb 1 '17 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.