Skip to content

Commit

Permalink
Merge branch '5.3' into 5
Browse files Browse the repository at this point in the history
  • Loading branch information
github-actions[bot] committed Dec 15, 2024
2 parents 4cd005f + 8ca581c commit c9c28be
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/Forms/SingleSelectField.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
60 changes: 59 additions & 1 deletion tests/php/Forms/DropdownFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public function testEmpty()

$form->method('getHTMLID')
->willReturn($formName);

$source = [
'first' => 'value',
0 => 'otherValue'
Expand Down Expand Up @@ -609,4 +609,62 @@ 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',
],
[
// 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());
}
}

0 comments on commit c9c28be

Please sign in to comment.