It's impossible to submit no value for a field that has a default value

Created on 19 August 2011, almost 14 years ago
Updated 25 June 2025, 21 days ago

Problem/Motivation

If you add a list field (any data type), set it to multiple and provide a default value, it is impossible to deselect all options for the field. The field system sees that that no values are supplied and supplies the default value on save. The default value populates the form for the field, so if the user explicitly unchecks them, the field system should not inject it's own defaults instead.

Proposed resolution

Indeed, I can reproduce with radios, checkboxes, but actually also for any field type and widget (e.g simple textfield widget for text or number fields).
1. Set a default value on a field
2. Go to the creation form for an entity using that field
3. Remove the pre-filled value (FAPI #default) and leave the field empty, save
4. The entity has the default value for the field.

This happens in field_default_insert(). Since #392696: Save default values on insert, default values get added on "entity insert" when the incoming $entity has no $entity->field_name property. That was to save default values on programmatic entity saves.
Later on, the 'Translatable fields' patch changed the condition, and default values get added also when
isset($entity->field_name[$langcode]) && count($entity->field_name[$langcode]) == 0
Yet $entity->field_name = array($langcode => array()) is exactly what comes out of any field that was left empty.

I cannot say I specifically remember the reasoning behind the code added by the TF patch, but it looks like we should rather check for !isset($entity->field_name[$langcode]).

We'll also need tests for this :-/.

Attachment Size Status Test result Operations
field_default_value-1253820-1.patchREVIEWSIMPLYTEST.ME 751 bytes Idle FAILED: [[SimpleTest]]: [MySQL] 33,661 pass(es), 1 fail(s), and 1 exception(es). View details | Re-test

Remaining tasks

(reviews needed, tests to be written or run, documentation to be written, etc.)

User interface changes

(New or changed features/functionality in the user interface, modules added or removed, changes to URL paths, changes to user interface text.)

API changes

(API changes/additions that would affect module, install profile, and theme developers, including examples of before/after code if appropriate.)

Related Issues

hook_entity_create() is invoked after creating a new entity object

Original report by fearlsgroove

πŸ› Bug report
Status

Fixed

Version

8.0 ⚰️

Component

field system

Created by

πŸ‡ΊπŸ‡ΈUnited States fearlsgroove

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