diff --git a/src/Forms/SingleSelectField.php b/src/Forms/SingleSelectField.php index 1cb8176783d..b2488c369cf 100644 --- a/src/Forms/SingleSelectField.php +++ b/src/Forms/SingleSelectField.php @@ -59,12 +59,13 @@ public function getValueForValidation(): mixed public function getDefaultValue() { $value = $this->Value(); + $validValues = $this->getValidValues(); // assign value to field, such as first option available - if ($value === null) { + if ($value === null || !in_array($value, $validValues)) { if ($this->getHasEmptyDefault()) { $value = ''; } else { - $values = $this->getValidValues(); + $values = $validValues; $value = array_shift($values); } } diff --git a/tests/php/Forms/DropdownFieldTest.php b/tests/php/Forms/DropdownFieldTest.php index 2e87284a7c3..8af81e7af1b 100644 --- a/tests/php/Forms/DropdownFieldTest.php +++ b/tests/php/Forms/DropdownFieldTest.php @@ -600,4 +600,62 @@ public function testEmptySourceDoesntBlockValidation() $field->setDisabledItems([ 'A', 'B' ]); $this->assertTrue($field->validate()->isValid()); } + + public function provideGetDefaultValue(): array + { + return [ + [ + 'value' => null, + 'hasEmptyDefault' => true, + 'expected' => '', + ], + [ + 'value' => null, + 'hasEmptyDefault' => false, + 'expected' => 'one', + ], + [ + 'value' => 'four', + 'hasEmptyDefault' => true, + 'expected' => '', + ], + [ + 'value' => 'four', + 'hasEmptyDefault' => false, + 'expected' => 'one', + ], + [ + 'value' => 'two', + 'hasEmptyDefault' => true, + 'expected' => 'two', + ], + [ + 'value' => 'two', + 'hasEmptyDefault' => false, + 'expected' => 'two', + ], + [ + // Note this is an int, but matches against the string key + 'value' => 3, + 'hasEmptyDefault' => true, + 'expected' => 3, + ], + [ + 'value' => 3, + 'hasEmptyDefault' => false, + 'expected' => 3, + ], + ]; + } + + /** + * @dataProvider provideGetDefaultValue + */ + public function testGetDefaultValue(mixed $value, bool $hasEmptyDefault, mixed $expected): void + { + $field = new DropdownField('MyField', source: ['one' => 'one', 'two' => 'two', '3' => 'three']); + $field->setHasEmptyDefault($hasEmptyDefault); + $field->setValue($value); + $this->assertSame($expected, $field->getDefaultValue()); + } }