list_field_is_empty() always returns FALSE for list_boolean fields

Created on 25 June 2013, over 11 years ago
Updated 25 February 2023, over 1 year ago

Problem/Motivation

Currently /core/modules/options/src/Plugin/Field/FieldType/ListItemBase::isEmpty() uses the following conditional to test whether a field is empty:

return empty($this->value) && (string) $this->value !== '0';

If the value of the field is also not zero, then it is empty. This seems fine for most list fields, but causes big problems when writing code for Boolean fields. One would reasonably expect this function to return TRUE for a value of 0, which in the context of a single on/off checkbox, is empty. However, this function will always return FALSE for Booleans, whether you pass it 0 or 1.

Proposed resolution

Update conditions for manage boolean fields.

Text of the original report by [venutip ]

Currently, list_field_is_empty() uses the following conditional to test whether a field is empty:

if (empty($item['value']) && (string) $item['value'] !== '0')

In other words, if the empty() function returns TRUE and the string value of the field is also not zero, then it is empty. This seems fine for most list fields, but causes big problems when writing code for Boolean fields. One would reasonably expect this function to return TRUE for a value of 0, which in the context of a single on/off checkbox, is empty. However, this function will always return FALSE for Booleans, whether you pass it 0 or 1.

One place where this causes problems is with field collections. Suppose you have a field collection that consists of two required fields and one optional Boolean (a single on/off checkbox). The field collection module uses the emptiness of the collection to decide whether to enforce validation of required fields. But because list_field_is_empty() always returns FALSE for single on/off checkboxes, the collection can never be considered empty.

The attached patch adds a check to see if we're dealing with a list_boolean field and, if so, considers 0 to be empty.

🐛 Bug report
Status

Needs work

Version

9.5

Component
Options 

Last updated 9 days ago

No maintainer
Created by

🇺🇸United States venutip

Live updates comments and jobs are added and updated live.
  • Novice

    It would make a good project for someone who is new to the Drupal contribution process. It's preferred over Newbie.

  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

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