FIX unrequire fields when they become dataless (#1016)

* FIX unrequire fields when they become dataless

When fields that collect input data are changed in configuration via the
CMS to become fields that no longer collect input data (e.g. TextField
-> HTML Block), submitting the resulting form results in a fatal error,
server 500 response, etc. due to trying to check if a field without data
(ever) has data in it.

To circumvent this we can set the required state to false if the field
is being converted to one that does not collect data (which FormField
API conveniently provides a check for).

* Move parent::onBeforeWrite() to top of function

Co-authored-by: Steve Boyd <emteknetnz@gmail.com>
This commit is contained in:
Dylan Wagstaff 2021-01-17 15:55:47 +13:00 committed by GitHub
parent a42729679b
commit c0a30f1b6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -413,6 +413,11 @@ class EditableFormField extends DataObject
{
parent::onBeforeWrite();
$formField = $this->getFormField();
if ($formField && !$formField->hasData()) {
$this->Required = false;
}
// Set a field name.
if (!$this->Name) {
// New random name

View File

@ -10,6 +10,7 @@ use SilverStripe\UserForms\Model\EditableFormField;
use SilverStripe\UserForms\Model\EditableFormField\EditableCheckbox;
use SilverStripe\UserForms\Model\EditableFormField\EditableDropdown;
use SilverStripe\UserForms\Model\EditableFormField\EditableFileField;
use SilverStripe\UserForms\Model\EditableFormField\EditableLiteralField;
use SilverStripe\UserForms\Model\EditableFormField\EditableOption;
use SilverStripe\UserForms\Model\EditableFormField\EditableRadioField;
use SilverStripe\UserForms\Model\EditableFormField\EditableTextField;
@ -292,4 +293,20 @@ class EditableFormFieldTest extends FunctionalTest
$field = $this->objFromFixture(EditableTextField::class, $fieldName);
$this->assertEquals($expected, $field->isDisplayed($data));
}
public function testChangingDataFieldTypeToDatalessRemovesRequiredSetting()
{
$requiredTextField = $this->objFromFixture(EditableTextField::class, 'required-text');
$fieldId = $requiredTextField->ID;
$this->assertTrue((bool)$requiredTextField->Required);
$literalField = $requiredTextField->newClassInstance(EditableLiteralField::class);
$this->assertTrue((bool)$literalField->Required);
$literalField->write();
$this->assertFalse((bool)$literalField->Required);
$updatedField = EditableFormField::get()->byId($fieldId);
$this->assertFalse((bool)$updatedField->Required);
}
}