Add support for directly saving into a File object

saveInto() assumed you were either saving into a hasOne or if you wanted to create a new object.

This made it impossible to have a FileField on an object that you wanted to upload to. This adds a check so that if the local object is a file, save to that.
This commit is contained in:
Will Rossiter 2014-08-31 15:55:51 +12:00
parent 4b6a03bb0b
commit 0991477e5a

View File

@ -99,29 +99,41 @@ class FileField extends FormField {
} }
public function saveInto(DataObjectInterface $record) { public function saveInto(DataObjectInterface $record) {
if(!isset($_FILES[$this->name])) return false; if(!isset($_FILES[$this->name])) {
$fileClass = File::get_class_for_file_extension(pathinfo($_FILES[$this->name]['name'], PATHINFO_EXTENSION)); return false;
}
$fileClass = File::get_class_for_file_extension(
pathinfo($_FILES[$this->name]['name'], PATHINFO_EXTENSION)
);
if($this->relationAutoSetting) { if($this->relationAutoSetting) {
// assume that the file is connected via a has-one // assume that the file is connected via a has-one
$hasOnes = $record->has_one($this->name); $hasOnes = $record->has_one($this->name);
// try to create a file matching the relation // try to create a file matching the relation
$file = (is_string($hasOnes)) ? Object::create($hasOnes) : new $fileClass(); $file = (is_string($hasOnes)) ? Object::create($hasOnes) : new $fileClass();
} else if($record instanceof File) {
$file = $record;
} else { } else {
$file = new $fileClass(); $file = new $fileClass();
} }
$this->upload->loadIntoFile($_FILES[$this->name], $file, $this->getFolderName()); $this->upload->loadIntoFile($_FILES[$this->name], $file, $this->getFolderName());
if($this->upload->isError()) return false;
if($this->upload->isError()) {
return false;
}
if($this->relationAutoSetting) {
if(!$hasOnes) {
return false;
}
$file = $this->upload->getFile(); $file = $this->upload->getFile();
if($this->relationAutoSetting) {
if(!$hasOnes) return false;
// save to record
$record->{$this->name . 'ID'} = $file->ID; $record->{$this->name . 'ID'} = $file->ID;
} }
return $this; return $this;
} }