Skip to content

Commit

Permalink
FIX Add extraEmptyValues to TreedropdownField
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Nov 8, 2023
1 parent 0ac8499 commit 0c6600b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/Forms/RequiredFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions src/Forms/TreeDropdownField.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
18 changes: 17 additions & 1 deletion tests/php/Forms/RequiredFieldsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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']));
}
}

0 comments on commit 0c6600b

Please sign in to comment.