From a9b737008fd7c4ca0485712d1e5ca171da664e51 Mon Sep 17 00:00:00 2001 From: Jake Bentvelzen Date: Mon, 1 May 2017 13:08:57 +1000 Subject: [PATCH] fix(Validation): Fix bug where saving an existing DataObject via a Form causes validate() to have the error: "Invalid file ID sent." --- code/FileAttachmentField.php | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/code/FileAttachmentField.php b/code/FileAttachmentField.php index 83b4a31..8f1931d 100644 --- a/code/FileAttachmentField.php +++ b/code/FileAttachmentField.php @@ -452,11 +452,39 @@ public function validate($validator) { } /** + * @param int|array $val + * @param array|DataObject $data * @return $this */ public function setValue($val, $data = array()) { + if (!$val && $data && $data instanceof DataObject && $data->exists()) { + // NOTE: This stops validation errors from occuring when editing + // an already saved DataObject. + $fieldName = $this->getName(); + $ids = array(); + if ($data->hasOneComponent($fieldName)) { + $id = $data->{$fieldName.'ID'}; + if ($id) { + $ids[] = $id; + } + } else if ($data->hasManyComponent($fieldName) || $data->manyManyComponent($fieldName)) { + $files = $data->{$fieldName}(); + if ($files) { + foreach ($files as $file) { + if (!$file->exists()) { + continue; + } + $ids[] = $file->ID; + } + } + } + if ($ids) { + $this->addValidFileIDs($ids); + } + } if ($data && is_array($data) && isset($data[$this->getName()])) { // Prevent Form::loadDataFrom() from loading invalid File IDs + // that may have been passed. $isInvalid = false; $validIDs = $this->getValidFileIDs(); // NOTE(Jake): If the $data[$name] is an array, its coming from 'loadDataFrom'