1

I create a custom entity (pool) with a custom form.

In my custom form, i have a field (start_date)

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => new DrupalDateTime()
];

When i want to save, i have the follow error :

"Data too long for column"

In the log, the value is : 2017-12-21 18:06:29 Europe/Paris Instead of 2017-12-21T17:06:29

What i'm doing wrong ?

2 Answers 2

2

Drupal's DateTime field isn't ISO 8601 compliant, (doesn't save datetime values in the standard format you're expecting 2017-12-21T17:06:29). You need to convert the value to UTC format for storage. One approach is to initialize a date variable, convert it, and then pass as the value in your form field.

$currentDate = new DrupalDateTime();
if ($currentDate instanceOf DrupalDateTime && !$currentDate->hasErrors()) {
  $currentDate->setTimezone(new \DateTimeZone('UTC');
  $db_friendly_value = $currentDate->format('Y-m-d\TH:i:s');
}

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => $db_friendly_value
];

Specific notes about working with the DateTime API in D8 can be found in this "New DateTime API" post.

This specific formatting issue was reported for the datetime module here.

Comment 6 shows the recommended approach to converting the date into the proper format for saving.

0
0

So with your advices, i found a solution :

      public function buildForm(array $form, FormStateInterface $form_state) {
        $form = parent::buildForm($form, $form_state);
        $entity = $this->entity;

        $currentDate = new DrupalDateTime();
           $form['start_date'] = [
           '#type' => 'datetime',
           '#title' => t('Start Date'),
           '#default_value' => $currentDate
        ];

I add the function validateForm and setValueForElement

public function validateForm(array &$form, FormStateInterface $form_state)
{
$entity = $this->getEntity();
$currentDate = $form_state->getValues()['start_date'];
if ($currentDate instanceOf DrupalDateTime && !$currentDate->hasErrors()) {
  $currentDate->setTimezone(new \DateTimeZone(DATETIME_STORAGE_TIMEZONE));
  $db_friendly_value = $currentDate->format(DATETIME_DATETIME_STORAGE_FORMAT);
}

$element[] = $db_friendly_value;

$element['#parents'] = ['start_date'];
$form_state->setValueForElement($element, $db_friendly_value);
$form_state->setTemporaryValue('entity_validated', TRUE);

}

And now it's ok in the db

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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