I want to edit a record in CakePhp without deleting the saved path of an uploaded jpg file. Right now when I edit the record it deletes the saved file path.
The approach I think would work is to do a logic 开发者_开发百科check in the form to check if the field is empty or not. Display the saved file path if it's not empty or show an empty path if it is. Would this be the best way to update the record?
I'm using Miles Johnson's uploader plugin for uploading files.
Here's the code within the form:
<?php
if (!empty ($slider ['Slider']['bgImg']));
echo $slider ['bgImg'];
else
echo $form->input('file', array('type' => 'file'));
?>
This logic should be in the controller, strictly speaking.
In my apps with files and edit capabilities, I will show a file field and a link/thumbnail of the image in question on the edit form.
my approach uses my own uploader, so your results may vary, but essentially:
if (!empty($this->data)) {
$file_object = $this->data['Listing']['featured_image'];
$image_data=$this->Upload->do_upload($file_object, 'img/uploads/');
if($image_data){
$this->data['Listing']['featured_image'] = $image_data['name'];
} else {
unset($this->data['Listing']['featured_image']);
}
$this->Listing->save($this->data)
and in my upload component, I have this:
public function do_upload($file_object, $location='img/uploads/') {
/**
* No file was uploaded
*/
if($file_object['error']==4) {
return false;
}
// carry on uploading
So essentially; I pass my upload component the $file_object
, which is from the form. I then do a simple test, using the default set of error codes to see if the file is empty (4). If it's empty, I return false. (you could return errors etc, but this was my approach).
after the upload call, I check the return value, and if the file was uploaded successfully, I can then set the field in my model. (the file name, in my case) - you may want to store the path as well, for instance.
If it's false - it means there was no file; so I unset the value from the array.
Because the field does not exist in the array, cake will not attempt to overwrite existing data - it simply ignores it; allowing the old value to stay untouched.
精彩评论