ListItemBase::generateSampleValue() white screen when options list is empty

Created on 5 January 2023, over 1 year ago
Updated 31 March 2023, about 1 year ago

Problem/Motivation

When loading an entity display configuration page (like `admin/structure/types/manage/page/display`) that uses Layout Builder, if the entity has an options field that has no options available, the page cannot be loaded due to a PHP error.

Steps to reproduce

First noted on PHP 8.1 and core 9.5.

Enable layout_builder. Configure your entity display to use Layout Builder.

Add a list_string field to your entity that uses an allowed_values_function. Have the allowed_values_function return an empty array. (you can also just install and enable the scheduler_content_moderation_integration module which provides two of these via hook_entity_base_field_info().) Or, just create an options field with no options.

Load the configuration page for your display mode. See:

`ValueError: array_rand(): Argument #1 ($array) cannot be empty in array_rand() (line 68 of /code/web/core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php)`

Proposed resolution

The error is caused by this code in `core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php`:

  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $allowed_options = options_allowed_values($field_definition->getFieldStorageDefinition());
    $values['value'] = array_rand($allowed_options);
    return $values;
  }

Because array_rand does not accept empty arrays.

I propose we check if the `$allowed_options` is empty, and if it is, return an empty value rather than invoking `array_rand()`.

(There seem to be a couple ā†’ issues šŸ› Layout builder's use of sample data can cause exceptions during rendering of default entity view displays Needs work attempting to resolve similar problems from the Layout Builder side, but this seems like an issue with this specific piece of code. "no options available" isn't an ideal result, but it is sensible in some use cases, and this code should handle those cases without crashing.)

Remaining tasks

May need a test.

User interface changes

None.

API changes

None?

Data model changes

N/A

Release notes snippet

Allow sample content to be generated for options fields with no valid options.

šŸ› Bug report
Status

Fixed

Version

9.5

Component
OptionsĀ  ā†’

Last updated 27 days ago

No maintainer
Created by

šŸ‡ŗšŸ‡øUnited States gcb

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.69.0 2024