SingleValueTrait doesn't allow for empty fields

Created on 15 November 2024, 2 months ago

Problem/Motivation

It would be nice to be able to use SingleValueTrait for fields of cardinalty 1, but that don't always have a value (like a non-required normal field).

At the moment you can't do that, and it's not obvious why.

Consider the following implementation:

singleComputeValue(EntityInterface $host_entity, ComputedFieldDefinitionWithValuePluginInterface $computed_field_definition): mixed {
  if (/* some condition */) {
    return 'some value';
  }
  else {
    return NULL;
  }
}

The trait produces these field values:

[
  0 => NULL,
]

This leads to some cryptic error messages down the line:

Warning: array_flip(): Can only flip string and integer values, entry skipped in Drupal\Core\Entity\EntityStorageBase->loadMultiple() (line 278 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).

The trait should probably produce this: (ie empty)

[].

Proposed resolution

Change SingleValueTrait as described. Also add something to the function's DocBlock to explain that returning NULL means "the field is empty".

Remaining tasks

Patch, test etc.

✨ Feature request
Status

Active

Version

4.0

Component

Code

Created by

πŸ‡ΈπŸ‡ͺSweden erik.erskine

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

Merge Requests

Comments & Activities

Production build 0.71.5 2024