I have a datetime field on a custom entity defined in baseFieldDefinitions(). This has set a default, which should be now. But when saving the entity, i get following error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'date' at row 1: INSERT INTO {sale} (uuid, langcode, user_id, name, status, created, changed, date, price, party) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 3e25c5cb-0092-42dd-914b-4e4b91bdcf19 [:db_insert_placeholder_1] => en [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => Jupiler [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => 1516504047 [:db_insert_placeholder_6] => 1516504047 [:db_insert_placeholder_7] => 2018-01-21 04:07:06 Europe/Brussels [:db_insert_placeholder_8] => 2 [:db_insert_placeholder_9] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->doSaveFieldItems() (line 878 of /var/www/drupalvm/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

This is my field definition:

$fields['date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Sale date'))
  ->setDescription(t('The date that the sale took place.'))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ->setDisplayOptions('form', array(
    'type' => 'date',
    'weight' => -4,
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)

How are datetime fields supposed to get a default value? If you look at the error, the value it tries to save is '2018-01-21 04:07:06 Europe/Brussels'.


As the BaseFieldDefenitions are cached, this won't work I believe.

I think you would be better off by using SetDefaultValueCallback:


| improve this answer | |
  • well, it actually tries to save a date if you look at the error: Data too long for column 'date' at row 1 ... [:db_insert_placeholder_7] => 2018-01-21 04:07:06 Europe/Brussels ... – betz Jan 22 '18 at 17:56
  • you could use the correct date format DATETIME_DATETIME_STORAGE_FORMAT, but this answer is about the main problem here, that you store the default date when the entity field definitions are rebuilt/cached and not when the entity is saved. – 4k4 Jan 22 '18 at 22:21

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.