Skip to content

Commit

Permalink
ENH Call getCMSCompositeValidator() when saving Link DataObjects
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Sep 26, 2023
1 parent ebf526b commit f483769
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Models/Link.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\View\Requirements;
use SilverStripe\Forms\Form;
use SilverStripe\ORM\ValidationResult;

/**
* A Link Data Object. This class should be a subclass, and you should never directly interact with a plain Link
Expand Down Expand Up @@ -110,6 +112,28 @@ public function getCMSCompositeValidator(): CompositeValidator
return $validator;
}

/**
* This method is used to validate the dataobject before saving as part of DataObject::write()
* Linkfield works a bit differently from normal forms, because where the modal data is turned
* into JSON and saved into a single JsonField and in saveInto() the JSON is loaded into the
* dataobject using DataObject::setData($data)
* Because of this alternate method of saving, the getCMSCompositeValidator() isn't called
* so we need to call it manually here by loading it into a temporary Form
*
* @return ValidationResult
*/
public function validate()
{
$parentResult = parent::validate();
$validator = $this->getCMSCompositeValidator();
$form = Form::create(null, Form::DEFAULT_NAME, $this->getCMSFields());
$form->setValidator($validator);
$form->loadDataFrom($this);
$formResult = $form->validationResult();
$combinedResult = $parentResult->combineAnd($formResult);
return $combinedResult;
}

/**
* Form hook defined in @see Form::saveInto()
* We use this to work with an in-memory only field
Expand Down

0 comments on commit f483769

Please sign in to comment.