Problem/Motivation

When creating a computed field and overriding FieldItemList, you must compute values when ::get is called and when ::getIterator is called. Failing to do so for either case leads to bugs that can be very difficult to track down.

Initially I ran into this here: #2817565: Bugs in ModerationStateFieldItemList mean it can never be used with a field formatter but I also ran into this again writing a test for #2852067: Add support for rendering computed fields to the "field" views field handler.

Proposed resolution

Introduce an abstract class which ensures values are calculated correctly for all of the required FieldItemList methods.

Remaining tasks

Discuss.

User interface changes

None.

API changes

API additions only.

Data model changes

None.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

Sam152 created an issue. See original summary.

Sam152’s picture

Issue summary: View changes
Sam152’s picture

Title: Introduce an abstract ComputedFieldItemList class to make the process of writing computed fields less error prone » Make the process of creating computed fields less bug prone
Status: Active » Needs review
FileSize
807 bytes

This is a possible implementation. It's a bit iffy in the sense it's not driven by an interface, but doing so would require exposing a public method, which I don't think is desirable here.

dawehner’s picture

This sounds interesting! Do you have an plans to let some of the core computed fields extends this class? I guess having a concrete example of this class could be helpful, even if it is just for documentation reasons.

Berdir’s picture

See #2846554: Make the PathItem field type actually computed and auto-load stored aliases, what I suggested there is to use #2392845: Add a trait to standardize handling of computed item lists for this, the pathauto issue also shows that this is needed on field item list and field item classes, and also the magic methods.

amateescu’s picture

Status: Needs review » Closed (duplicate)

Let's do this in the existing issue for "fixing" computed fields: #2392845: Add a trait to standardize handling of computed item lists