From d265c9b733ddac27d6df286ce000b09e1c69b986 Mon Sep 17 00:00:00 2001 From: Loz Calver Date: Mon, 14 Dec 2015 16:41:18 +0000 Subject: [PATCH] FIX: Allow omitting a value for OptionsetField submissions (fixes #4824) --- forms/OptionsetField.php | 11 +++++++++++ tests/forms/OptionsetFieldTest.php | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/forms/OptionsetField.php b/forms/OptionsetField.php index d5974314d..ecc4e8223 100644 --- a/forms/OptionsetField.php +++ b/forms/OptionsetField.php @@ -117,6 +117,17 @@ class OptionsetField extends DropdownField { return $this->disabledItems; } + /** + * {@inheritdoc} + */ + public function validate($validator) { + if (!$this->value) { + return true; + } + + return parent::validate($validator); + } + public function ExtraOptions() { return new ArrayList(); } diff --git a/tests/forms/OptionsetFieldTest.php b/tests/forms/OptionsetFieldTest.php index 8aa6c858b..d07f698af 100644 --- a/tests/forms/OptionsetFieldTest.php +++ b/tests/forms/OptionsetFieldTest.php @@ -25,6 +25,35 @@ class OptionsetFieldTest extends SapphireTest { ); } + public function testValidation() { + $field = OptionsetField::create('Test', 'Testing', array( + "One" => "One", + "Two" => "Two", + "Five" => "Five" + )); + $validator = new RequiredFields('Test'); + $form = new Form($this, 'Form', new FieldList($field), new FieldList(), $validator); + + $field->setValue("One"); + $this->assertTrue($field->validate($validator)); + + //non-existent value should make the field invalid + $field->setValue("Three"); + $this->assertFalse($field->validate($validator)); + + //empty string should pass field-level validation... + $field->setValue(''); + $this->assertTrue($field->validate($validator)); + + // ... but should not pass "RequiredFields" validation + $this->assertFalse($form->validate()); + + //disabled items shouldn't validate + $field->setDisabledItems(array('Five')); + $field->setValue('Five'); + $this->assertFalse($field->validate($validator)); + } + public function testReadonlyField() { $sourceArray = array(0 => 'No', 1 => 'Yes'); $field = new OptionsetField('FeelingOk', 'are you feeling ok?', $sourceArray, 1);