2

When I use datetime field without date I get the message below. I want to provide a field for time only.

Error message

This code is correct but still has the problem of the time field.

<?php

namespace Drupal\ets\Form\Sejours_sportifs;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;
use Drupal\file\Entity\File;

/**
 * Class SejourSportif.
 */
class SejourSportif extends FormBase {
  public $liste = array();

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'sejour_sportif';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#cache'] = ['max-age' => 0];

    $this->connection = Database::getConnection();
    $connection = Database::getConnection();
    $req = "SELECT id, name FROM details_types_sejours_field_data;";
    $reponse = $connection->query($req);
    $results = $reponse->fetchAll();
    $this->liste += [
          '0' => t('Choose'),
    ];
    foreach ($results as $result){
      $this->liste += [
          $result->id => $result->name,
      ];
    }
    $header = array();
    $header['journee'] = $this->t('Stays days');
    $header['matin'] = $this->t('Morning');
    $header['soir'] = $this->t('Evening');
    $header['observations'] = $this->t('Comments');
    $header['operation'] = $this->t('Action');

    $promoted_items = array();
    $number_promoted = $form_state->getValue('number_promoted', count($promoted_items));
    $removed = $form_state->getValue('removed_promoted', []);

    $form['number_promoted'] = [
      '#type' => 'value',
      '#value' => $number_promoted,
    ];
    $form['removed'] = [
      '#type' => 'value',
      '#value' => $removed,
    ];
    $form['promoted'] = array(
      '#type' => 'table',
      '#header' => $header,
      '#title' => t("Days number"),
      '#tree' => TRUE,
    );
    for ($i = 1; $i <= $number_promoted; $i++) {
      $form['#cache'] = ['max-age' => 0];
      $item = array_shift($promoted_items);
      if (in_array($i, $removed)) {continue;}
      $form['promoted-container'] = [
        '#type' => 'container',
        '#title' => t("Day number #@i", ['@i' => $i]),
      ];

      // Journée

      $form['promoted'][$i] = [
        'journee' => array(
          '#type' => 'date',
          '#title' => $this->t('Stays'),
          //'#default_value' => $item['title'],
        ),

        // Matin

        'matin' => array(
          array(
            '#type' => 'datetime',
            '#title' => $this->t("Start hour"),
            '#date_date_element' => 'none', // hide date element 
            '#date_time_element' => 'time', // you can use text element here as well 
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'datetime',
            '#title' => $this->t("End hour"),
            //'#default_value' => $item['title'],
            '#date_date_element' => 'none', // hide date element 
            '#date_time_element' => 'time', // you can use text element here as well 
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'select',
            '#default_value' => 'Choose',
            '#options' => $this->liste,
            '#title' => $this->t('Requested service:'),
          )
        ),

        // Soir

        'soir'=>array(
          array(
            '#type' => 'datetime',
            '#title' => $this->t("Start hour"),
            //'#default_value' => $item['title'],
            '#date_date_element' => 'none', // hide date element 
            '#date_time_element' => 'time', // you can use text element here as well 
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'datetime',
            '#title' => $this->t("End hour"),
            //'#default_value' => $item['title'],
            '#date_date_element' => 'none', // hide date element 
            '#date_time_element' => 'time', // you can use text element here as well 
            '#date_time_format' => 'H:i',
            '#default_value' => '00:00',
          ),
          array(
            '#type' => 'select',
            '#default_value' => 'Choose',
            '#options' => $this->liste,
            '#title' => $this->t('Requested service:'),
          )
        ),

        // Observations

        'observations' => array(
          '#type' => 'textarea',
          '#title' => $this->t('Comments:'),
          '#cols' => '20',
          '#rows' => '5',
        ),
      ];

      // Boutons

      $form['promoted'][$i]['remove_' . $i] = [
        '#type' => 'submit',
        '#value' => t("Delete stays #@i", ['@i' => $i]),
        '#submit' => ['::removeItem'],
        '#attributes' => [
          'class' => ['button--danger'],
          'data-toRemove' => $i,
        ],
      ];
    }

    $form['#cache'] = ['max-age' => 0];
    $form['promoted-container'] = [
      '#type' => 'submit',
      '#value' => t('Add new stays'),
      '#submit' => ['::addPromotedItem'],
    ];

    return $form;
  }


  public function addPromotedItem(array &$form, FormStateInterface $form_state) {
    $form['#cache'] = ['max-age' => 0];

    $form_state->setValue('number_promoted', $form_state->getValue('number_promoted') + 1);
    $form_state->setRebuild();
  }

  public function removeItem(array &$form, FormStateInterface $form_state) {
    //$form['#cache'] = ['max-age' => 0];

    /*$removed[] = $form_state->getTriggeringElement()['#attributes']['data-toRemove'];

    if(count($promoted)>1){
      // Find the key of the item we need to remove
      $removed = array_search($data-toRemove, 'promoted');

      // Remove our triggered element
      unset($[$key_to_remove]);

      // Rebuild the field deltas values
      $form_state->set('field_froid_ferme', $field_livraisons_array);

      // Rebuild the form
      $form_state->setRebuild();
    }else{
    */


    $removed = $form_state->getValue('removed_promoted');
    $removed[] = $form_state->getTriggeringElement()['#attributes']['data-toRemove'];
    $form_state->setValue('removed_promoted', $removed);
    unset($removed[count($removed)-1]);
    $form_state->setValue('number_promoted', $form_state->getValue('number_promoted') - 1);
    //$form_state->setValue('removed_promoted', $removed);
    $form_state->setRebuild();
    $form_state->setValue('removed_promoted', $removed);
  }



  public function validateForm(array &$form, FormStateInterface $form_state) {
    //parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Display result.
    /*foreach ($form_state->getValues() as $key => $value) {
      //drupal_set_message($key . ': ' . $value);
    }
    */
  }

}
  • Can you share how you removed the date field from the datetime field? Maybe answer lies in there. – sorabh.v6 May 10 '18 at 8:13
  • $form['time_container']['time'] = [ '#type' => 'datetime', '#title' => $this->t('Time'), '#size' => 20, '#date_date_element' => 'none', // hide date element '#date_time_element' => 'time', // you can use text element here as well '#date_time_format' => 'H:i' ]; – Ghanmi Kais May 10 '18 at 10:00
  • I added the datetime field using the UI and then in the code I hid the #date_date_element as you are doing in your code. And it's working fine and not showing any error. However on content display it was showing the full datetime which I corrected by using the datetime custom field formatter. – sorabh.v6 May 10 '18 at 10:10
  • There is new module to provide you time_field " drupal.org/project/time_field " – Lost Koder Jul 12 '18 at 9:33
3

It looks like your #default_value is undefined. I suggest you add the default value for the field too. Like this -

$form['time_container']['time'] = [
  '#type' => 'datetime',
  '#title' => $this->t('Time'),
  '#size' => 20,
  '#date_date_element' => 'none', // hide date element
  '#date_time_element' => 'time', // you can use text element here as well
  '#date_time_format' => 'H:i',
  '#default_value' => '00:00',
 ];
|improve this answer|||||
  • when I add new line in my form, only the values in time fields are missed !!! – Ghanmi Kais May 10 '18 at 22:40
  • New line like <br> in the #markup or something else. Can you update the question with the code you are using for the form? – sorabh.v6 May 11 '18 at 6:49

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.