Skip to content

Commit

Permalink
FIX unrequire fields when they become dataless (#1016)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
NightJar and emteknetnz authored Jan 17, 2021
1 parent a427296 commit c0a30f1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions code/Model/EditableFormField.php
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,11 @@ public function onBeforeWrite()
{
parent::onBeforeWrite();

$formField = $this->getFormField();
if ($formField && !$formField->hasData()) {
$this->Required = false;
}

// Set a field name.
if (!$this->Name) {
// New random name
Expand Down
17 changes: 17 additions & 0 deletions tests/Model/EditableFormFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
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;
Expand Down Expand Up @@ -292,4 +293,20 @@ public function testIsDisplayed($fieldName, $data, $expected)
$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);
}
}

0 comments on commit c0a30f1

Please sign in to comment.