From 5b450f7feaf4d2ca90dee5fda504479e288789cd Mon Sep 17 00:00:00 2001 From: Sam Minnee Date: Fri, 11 Jan 2013 17:34:27 +1300 Subject: [PATCH] NEW: Added replaceExistingFile setting for UploadField. Sometimes has-one UploadFields can get confused about whether or not there is an existing file that needs deleting. This setting lets you make a more robust has-one UploadField, where any existing file will be replaced. It more closely mimics simple single-file upload fields. --- _config/uploadfield.yml | 1 + forms/UploadField.php | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/_config/uploadfield.yml b/_config/uploadfield.yml index 4639af322..ccd35fbf8 100644 --- a/_config/uploadfield.yml +++ b/_config/uploadfield.yml @@ -6,6 +6,7 @@ UploadField: allowedMaxFileNumber: canUpload: true canAttachExisting: 'CMS_ACCESS_AssetAdmin' + replaceExistingFile: false previewMaxWidth: 80 previewMaxHeight: 60 uploadTemplateName: 'ss-uploadfield-uploadtemplate' diff --git a/forms/UploadField.php b/forms/UploadField.php index a72bc3883..2766b028f 100644 --- a/forms/UploadField.php +++ b/forms/UploadField.php @@ -93,6 +93,13 @@ class UploadField extends FileField { * String values are interpreted as permission codes. */ 'canAttachExisting' => "CMS_ACCESS_AssetAdmin", + /** + * @var boolean If a second file is uploaded, should it replace the existing one rather than throwing an errror? + * This only applies for has_one relationships, and only replaces the association + * rather than the actual file database record or filesystem entry. + */ + 'replaceExistingFile' => false, + /** * @var int */ 'previewMaxWidth' => 80, @@ -487,6 +494,10 @@ class UploadField extends FileField { $tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber'); // has_one only allows one file at any given time. } elseif($record->has_one($name)) { + // If we're allowed to replace an existing file, clear out the old one + if($record->$name && $this->getConfig('replaceExistingFile')) { + $record->$name = null; + } $tooManyFiles = $record->{$name}() && $record->{$name}()->exists(); }