FIX: Don’t break validation on selects without a source.

Fixes cases where there are no valid values or an empty-string
value is manually added rather than using setEmptyString()

Fixes #4849
Fixes #7159
This commit is contained in:
Sam Minnee 2018-10-06 11:53:17 +13:00
parent 28c12bfec9
commit e5d3b28a4d
2 changed files with 34 additions and 3 deletions

View File

@ -124,15 +124,17 @@ abstract class SingleSelectField extends SelectField
{
// Check if valid value is given
$selected = $this->Value();
$validValues = $this->getValidValues();
if (strlen($selected)) {
// Use selection rules to check which are valid
foreach ($this->getValidValues() as $formValue) {
foreach ($validValues as $formValue) {
if ($this->isSelectedValue($formValue, $selected)) {
return true;
}
}
} else {
if ($this->getHasEmptyDefault()) {
if ($this->getHasEmptyDefault() || !$validValues || in_array('', $validValues)) {
// Check empty value
return true;
}

View File

@ -505,7 +505,7 @@ class DropdownFieldTest extends SapphireTest
*/
public function testRequiredDropdownHasEmptyDefault()
{
$field = new \SilverStripe\Forms\DropdownField("RequiredField", "dropdown", ["item 1", "item 2"]);
$field = new DropdownField("RequiredField", "dropdown", ["item 1", "item 2"]);
$form = new Form(
Controller::curr(),
@ -517,4 +517,33 @@ class DropdownFieldTest extends SapphireTest
$this->assertTrue($field->getHasEmptyDefault());
}
public function testEmptySourceDoesntBlockValidation()
{
// Empty source
$field = new DropdownField("EmptySource", "", []);
$v = new RequiredFields();
$field->validate($v);
$this->assertTrue($v->getResult()->isValid());
// Source with a setEmptyString
$field = new DropdownField("EmptySource", "", []);
$field->setEmptyString('(Select one)');
$v = new RequiredFields();
$field->validate($v);
$this->assertTrue($v->getResult()->isValid());
// Source with an empty value
$field = new DropdownField("SourceWithBlankVal", "", [ "" => "(Choose)" ]);
$v = new RequiredFields();
$field->validate($v);
$this->assertTrue($v->getResult()->isValid());
// Source with all items disabled
$field = new DropdownField("SourceWithBlankVal", "", [ "A" => "A", "B" => "B" ]);
$field->setDisabledItems([ 'A', 'B' ]);
$v = new RequiredFields();
$field->validate($v);
$this->assertTrue($v->getResult()->isValid());
}
}