Skip to content

Commit

Permalink
FIX Retain value that failed validation on client side
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Aug 31, 2021
1 parent f626840 commit 2da5c6f
Show file tree
Hide file tree
Showing 9 changed files with 222 additions and 11 deletions.
2 changes: 1 addition & 1 deletion client/dist/js/bundle.js

Large diffs are not rendered by default.

33 changes: 27 additions & 6 deletions client/src/legacy/ElementEditor/entwine.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { destroy } from 'redux-form';

/**
* Reset the Apollo and Redux stores holding data relating to elemental inline edit forms
*
* @param {Array} invalidFieldNames Field names that failed server-side validation
*/
const resetStores = () => {
// After page level saves we need to reload all the blocks from the server. We can remove
Expand Down Expand Up @@ -60,16 +62,35 @@ jQuery.entwine('ss', ($) => {
},

onunmatch() {
resetStores();
// Reset the store if the user navigates to a different part of the CMS
// Ensure there is not a form submission in progress, as this handler will
// also be triggered from a form submission
if (this.attr('data-submitting-element-editor') !== '1') {
resetStores();
}
ReactDOM.unmountComponentAtNode(this[0]);
},

/**
* Invalidate cache after the form is submitted to force apollo to re-fetch.
*/
'from .cms-container': {
onsubmitform() {
this.attr('data-submitting-element-editor', '1');
}
},

'from .cms-edit-form': {
onaftersubmitform() {
resetStores();
onaftersubmitform(event, data) {
this.attr('data-submitting-element-editor', null);
const validationResultPjax = JSON.parse(data.xhr.responseText).ValidationResult;
const validationResult = JSON.parse(validationResultPjax.replace(/<\/?script[^>]*?>/g, ''));

// Reset redux store if form is succesfully submitted so apollo to refetches element data
// Do not rest if there are any validation errors from either the ElementalAreaField or a
// regular page field because we want redux to hydrate the form, rather than then refetching
// which will return a value from the database. Instead the user should still
// see any modfied value they just entered, whether valid or invalid
if (validationResult.isValid) {
resetStores();
}
}
},
});
Expand Down
10 changes: 10 additions & 0 deletions src/Extensions/ElementalAreasExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
use DNADesign\Elemental\Forms\ElementalAreaField;
use DNADesign\Elemental\Models\BaseElement;
use DNADesign\Elemental\Models\ElementalArea;
use DNADesign\Elemental\Validators\ElementalAreasValidator;
use SilverStripe\CMS\Model\RedirectorPage;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\CMS\Model\VirtualPage;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Extensible;
use SilverStripe\Forms\CompositeValidator;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\DataExtension;
Expand Down Expand Up @@ -243,6 +245,14 @@ public function onBeforeWrite()
}
}

/**
* @param CompositeValidator $compositeValidator
*/
public function updateCMSCompositeValidator(CompositeValidator $compositeValidator): void
{
$compositeValidator->addValidator(ElementalAreasValidator::create());
}

/**
* @return boolean
*/
Expand Down
17 changes: 16 additions & 1 deletion src/Forms/EditFormFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

namespace DNADesign\Elemental\Forms;

use DNADesign\Elemental\Models\BaseElement;
use SilverStripe\Control\RequestHandler;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Forms\DefaultFormFactory;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FormField;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
use SilverStripe\Forms\HTMLEditor\TinyMCEConfig;

Expand Down Expand Up @@ -37,8 +39,8 @@ public function getForm(RequestHandler $controller = null, $name = self::DEFAULT
// Namespace all fields - do this after getting getFormFields so they still get populated
$formFields = $form->Fields();
$this->namespaceFields($formFields, $context);
$this->addClassNameField($formFields, $context['Record']);
$form->setFields($formFields);

return $form;
}

Expand Down Expand Up @@ -72,4 +74,17 @@ protected function namespaceFields(FieldList $fields, array $context)
$field->setName($namespacedName);
}
}

/**
* @param FieldList $formFields
* @param BaseElement $record
*/
private function addClassNameField(FieldList $formFields, BaseElement $record)
{
$fieldName = sprintf(self::FIELD_NAMESPACE_TEMPLATE, $record->ID, 'ClassName');
$formFields->addFieldsToTab(
'Root.Main',
new HiddenField($fieldName, 'ClassName', get_class($record))
);
}
}
132 changes: 132 additions & 0 deletions src/Validators/ElementalAreasValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace DNADesign\Elemental\Validators;

use DNADesign\Elemental\Controllers\ElementalAreaController;
use DNADesign\Elemental\Forms\EditFormFactory;
use DNADesign\Elemental\Models\BaseElement;
use DNADesign\Elemental\Models\ElementalArea;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\Validator;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\ValidationResult;

class ElementalAreasValidator extends Validator
{
/**
* @param array $data
*/
public function php($data)
{
$valid = true;
$areaErrors = [];
$areaFieldNames = $this->getElementalAreaFieldNames($data['ClassName']);
foreach ($areaFieldNames as $areaFieldName) {
$elementsData = $data[$areaFieldName] ?? [];
if (empty($elementsData)) {
continue;
}
foreach (array_values($elementsData) as $elementData) {
$elementID = $this->getElementID($elementData);
if (!$elementID) {
continue;
}
$key = sprintf(EditFormFactory::FIELD_NAMESPACE_TEMPLATE, $elementID, 'ClassName');
$className = $elementData[$key] ?? '';
if (!$className) {
continue;
}
/** @var BaseElement $element */
$element = DataObject::get_by_id($className, $elementID, false);
if (!$element) {
continue;
}
$originalTitle = $element->Title ??
sprintf('(Untitled %s)', ucfirst($element->config()->get('singular_name')));
$formData = ElementalAreaController::removeNamespacesFromFields($elementData, $elementID);
$element->updateFromFormData($formData);
/** @var ValidationResult $validationResult */
$validationResult = $element->validate();
if ($validationResult->isValid()) {
continue;
}
if (!array_key_exists($areaFieldName, $areaErrors)) {
$areaErrors[$areaFieldName] = [
'The elements below have the following errors:' // TODO _t()
];
}
foreach ($validationResult->getMessages() as $message) {
$this->validationError(
"PageElements_{$elementID}_{$message['fieldName']}",
$message['message'],
$message['messageType'],
$message['messageCast']
);
$areaErrors[$areaFieldName][] = sprintf(
'%s - %s',
$originalTitle,
$message['message']
);
}
$valid = false;
}
}
if (!$valid) {
foreach ($areaErrors as $areaFieldName => $errors) {
$this->validationError(
$areaFieldName,
implode('<br>', $errors),
ValidationResult::TYPE_ERROR,
ValidationResult::CAST_HTML
);
}
// TODO: see what happens when you have multiple cms tabs
// Show a generic form message. Ideally this would be done in admin LeftAndMain.EditForm.js
// TODO: this is defined in en.js, needs to be in en.yml too (preferably admin, not elemental)
$msg = _t(
'VALIDATION_ERRORS_ON_PAGE',
'There are validation errors on this page, please fix them before saving or publishing.'
);
// If message above is change to javascript, instead set a blank string here to hide the
// generic form message by overriding any PageElement_3_Title type of message which will
// show as a generic form message since it won't match dataFieldByName($field) in
// Form::loadMessageFrom($data)
$this->validationError('GenericFormMessage', $msg);
}
return $valid;
}

/**
* @param string $parentClassName
* @return array
*/
private function getElementalAreaFieldNames(string $parentClassName): array
{
$fieldNames = [];
$hasOnes = Config::inst()->get($parentClassName, 'has_one');
foreach ($hasOnes as $fieldName => $className) {
if (!(Injector::inst()->get($className) instanceof ElementalArea)) {
continue;
}
$fieldNames[] = $fieldName;
}
return $fieldNames;
}

/**
* @param array $elementData
* @return string
*/
private function getElementID(array $elementData): string
{
foreach (array_keys($elementData) as $key) {
$rx = str_replace(['%d', '%s'], ['([0-9]+)', '(.+)'], EditFormFactory::FIELD_NAMESPACE_TEMPLATE);
if (!preg_match("#^{$rx}$#", $key, $match)) {
continue;
}
return $match[1];
}
return '';
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
<div $AttributesHTML data-schema="$SchemaData.JSON">
<%-- Field is rendered by React components --%>
<div>
<% if $Message %><span class="message $MessageType">$Message</span><% end_if %>
<div $AttributesHTML data-schema="$SchemaData.JSON">
<%-- Field is rendered by React components --%>
</div>
</div>

2 changes: 1 addition & 1 deletion tests/Behat/Context/FixtureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function theHasAContentElementWithContent($type, $pageTitle, $elementTitl
*/
public function contentBlocksAreNotInLineEditable()
{
$contentBlockClass = ElementContent::class;
$contentBlockClass = TestElementContent::class;
$config = <<<YAML
---
Name: testonly-content-blocks-not-inline-editable
Expand Down
7 changes: 7 additions & 0 deletions tests/Behat/features/edit-block-element.feature
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ Feature: Edit elements in the CMS
And I should see "Alice's Block"
And I should see "Bob's Block"

@sboyd
Scenario: I retain invalid values client-side
When I click on block 1
Then I should see "Alice's Block"
# Then I change Title
# and i save the page

Scenario: I can edit a non in-line editable block
Given content blocks are not in-line editable
And I go to "/admin/pages"
Expand Down
22 changes: 22 additions & 0 deletions tests/Src/TestContentElement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace DNADesign\Elemental\Tests\Src;

use DNADesign\Elemental\Models\ElementContent;
use SilverStripe\Dev\TestOnly;

class TestContentElement extends ElementContent implements TestOnly
{
public const INVALID_TITLE = 'INVALID_TITLE';

public const INVALID_TITLE_MESSAGE = 'INVALID_TITLE_MESSAGE';

public function validate()
{
$validationResult = parent::validate();
if ($this->Content === static::INVALID_TITLE) {
$validationResult->addFieldError('Content', static::INVALID_TITLE_MESSAGE);
}
return $validationResult;
}
}

0 comments on commit 2da5c6f

Please sign in to comment.