diff --git a/src/Forms/RequiredFields.php b/src/Forms/RequiredFields.php index d7c725bafec..e1ff9fed962 100644 --- a/src/Forms/RequiredFields.php +++ b/src/Forms/RequiredFields.php @@ -116,8 +116,15 @@ public function php($data) $error = (count($value ?? [])) ? false : true; } } else { - // assume a string or integer - $error = (strlen($value ?? '')) ? false : true; + $stringValue = (string) $value; + if ($formField instanceof TreeDropdownField) { + // test for blank string as well as '0' (relationID that hasn't been set) because FormBuilder + // forms created using redux-form may have a blank string for newly created records since the + // form wasn't populated with existing data + $error = in_array($stringValue, ['', '0']); + } else { + $error = strlen($stringValue) > 0 ? false : true; + } } if ($formField && $error) { diff --git a/src/Forms/TreeDropdownField.php b/src/Forms/TreeDropdownField.php index e61e5411dd4..77c8cbb1890 100644 --- a/src/Forms/TreeDropdownField.php +++ b/src/Forms/TreeDropdownField.php @@ -984,4 +984,16 @@ public function setShowSelectedPath($showSelectedPath) $this->showSelectedPath = $showSelectedPath; return $this; } + + /** + * @return array + */ + public function getSchemaValidation() + { + $validationList = parent::getSchemaValidation(); + if (array_key_exists('required', $validationList)) { + $validationList['required'] = ['extraEmptyValues' => ['0']]; + } + return $validationList; + } } diff --git a/tests/php/Forms/RequiredFieldsTest.php b/tests/php/Forms/RequiredFieldsTest.php index f620a63c16e..7da79eda213 100644 --- a/tests/php/Forms/RequiredFieldsTest.php +++ b/tests/php/Forms/RequiredFieldsTest.php @@ -4,10 +4,12 @@ use SilverStripe\Dev\SapphireTest; use SilverStripe\Forms\RequiredFields; +use SilverStripe\Forms\Form; +use SilverStripe\Forms\TreeDropdownField; +use SilverStripe\Security\Group; class RequiredFieldsTest extends SapphireTest { - public function testConstructingWithArray() { //can we construct with an array? @@ -286,4 +288,18 @@ public function testFieldIsRequired() "Unexpectedly returned true for a non-existent field" ); } + + public function testTreedropFieldValidation() + { + $form = new Form(); + $field = new TreeDropdownField('TestField', 'TestField', Group::class); + $form->Fields()->push($field); + $validator = new RequiredFields('TestField'); + $validator->setForm($form); + // blank string and '0' are fail required field validation + $this->assertFalse($validator->php(['TestField' => ''])); + $this->assertFalse($validator->php(['TestField' => '0'])); + // '1' passes required field validation + $this->assertTrue($validator->php(['TestField' => '1'])); + } }