Entity Base Field can't be saved as empty string from form (including as default)

Created on 4 March 2018, almost 7 years ago
Updated 27 August 2024, 4 months ago

Problem/Motivation

It should be possible to save the empty string '' on a non-compulsory string entity base field.

Create a field on an entity:

     $fields['string_field'] = BaseFieldDefinition::create('string')
        ->setLabel(t('Non-compulsory string field'))
        ->setDefaultValue('')
        ->setRequired(FALSE);

This will allow you to enter the field empty.

WidgetBase::extractFormValues() {
line 371: $items->setValue($values);
// Adds the blank item
372: $items->filterEmptyItems();
// Filters out the empty items.
// So the field list is an empty array.
}

So by this point $entity->fields['string_field']['x-default']->list = [];. This gets retrieved and cast to NULL before saving the entity, causing an SQL Integrity constraint violation: 1048 Column 'string_field'; cannot be null rather than saving a Default value.

Possibly related #2567899: Empty node titles cause failures when migrating because empty strings are treated as NULL although not cause by removing the value when extracting the values from a form.

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

🐛 Bug report
Status

Closed: works as designed

Version

8.6 ⚰️

Component
Field 

Last updated 1 day ago

Created by

🇳🇱Netherlands ekes

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024