Unverified Commit a09a2dee authored by Alex Pott's avatar Alex Pott
Browse files

fix: #3593223 [PHP 8.5] OptionsWidgetBase::getSelectedOptions tries to access...

fix: #3593223 [PHP 8.5] OptionsWidgetBase::getSelectedOptions tries to access null array key in some scenarios

By: herved
By: smustgrave
(cherry picked from commit 95b76594e9ac4e981cc5c2f89a5c5215435faef7)
parent 106d0215
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -187,7 +187,7 @@ protected function getSelectedOptions(FieldItemListInterface $items) {
      $value = $item->{$this->column};
      // Keep the value if it actually is in the list of options (needs to be
      // checked against the flat list).
      if (isset($flat_options[$value])) {
      if ($value !== NULL && isset($flat_options[$value])) {
        $selected_options[] = $value;
      }
    }
+20 −0
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\options_test\Plugin\Field\FieldWidget;

use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Widget extending OptionsSelectWidget without declaring multiple_values.
 */
#[FieldWidget(
  id: 'options_select_no_multiple',
  label: new TranslatableMarkup('Options select (no multiple_values)'),
  field_types: ['list_integer', 'list_float', 'list_string'],
)]
class OptionsSelectNoMultipleWidget extends OptionsSelectWidget {
}
+42 −0
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Tests\options\Kernel;

use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\entity_test\Entity\EntityTest;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests OptionsWidgetBase.
 */
#[CoversClass(OptionsWidgetBase::class)]
#[Group('options')]
#[RunTestsInSeparateProcesses]
class OptionsWidgetBaseTest extends OptionsFieldUnitTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['options', 'options_test'];

  /**
   * Tests that getSelectedOptions() skips NULL item values.
   */
  public function testGetSelectedOptionsWithNullValue(): void {
    \Drupal::service('entity_display.repository')
      ->getFormDisplay('entity_test', 'entity_test')
      ->setComponent($this->fieldName, ['type' => 'options_select_no_multiple'])
      ->save();

    // An entity with no value triggers formMultipleElements() which appends
    // an item with value = NULL before calling getSelectedOptions().
    $entity = EntityTest::create();
    $form = \Drupal::service('entity.form_builder')->getForm($entity);
    $this->assertSame([], $form[$this->fieldName]['widget'][0]['#default_value']);
  }

}