From 0e7a0439765a3c9c1052645c4042fba56dd16d98 Mon Sep 17 00:00:00 2001 From: Guy Sartorelli Date: Fri, 13 Dec 2024 09:24:46 +1300 Subject: [PATCH] FIX Treat value not in SingleSelectField options as blank This makes the react dropdown fields behave more like the entwine ones when the DB value is not in the set of dropdown options. --- src/Forms/SingleSelectField.php | 5 +-- tests/php/Forms/DropdownFieldTest.php | 49 ++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/Forms/SingleSelectField.php b/src/Forms/SingleSelectField.php index 1dcd6b502ed..44b1a7619ee 100644 --- a/src/Forms/SingleSelectField.php +++ b/src/Forms/SingleSelectField.php @@ -53,12 +53,13 @@ public function getSchemaDataDefaults() 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 88603aa7550..e965b762160 100644 --- a/tests/php/Forms/DropdownFieldTest.php +++ b/tests/php/Forms/DropdownFieldTest.php @@ -170,7 +170,7 @@ public function testEmpty() $form->method('getHTMLID') ->willReturn($formName); - + $source = [ 'first' => 'value', 0 => 'otherValue' @@ -609,4 +609,51 @@ public function testEmptySourceDoesntBlockValidation() $field->validate($v); $this->assertTrue($v->getResult()->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', + ], + ]; + } + + /** + * @dataProvider provideGetDefaultValue + */ + public function testGetDefaultValue(mixed $value, bool $hasEmptyDefault, mixed $expected): void + { + $field = new DropdownField('MyField', source: ['one' => 'one', 'two' => 'two', 'three' => 'three']); + $field->setHasEmptyDefault($hasEmptyDefault); + $field->setValue($value); + $this->assertSame($expected, $field->getDefaultValue()); + } }