In my edit function I have an image upload but when I go to the edit page, the file from the add page doesn’t stick and the image has to be uploaded again. I want the image to show up in the edit page so it can be submitted without having to upload the image again. I have no idea how to accomplish this.
public function edit($id = null) {
$bio = $this->Bios->get($id, [
'contain' => [],
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$bio = $this->Bios->patchEntity($bio, $this->request->getData());
if(!$bio->getErrors()) {
if (!empty($this->request->getData('resize_to_thumb'))) {
$resize_to_thumb=$this->request->getUploadedFile('resize_to_thumb');
if ($resize_to_thumb->getError() == 0) {
$destination = WWW_ROOT.'img'.DS.'bio_images'.DS.$resize_to_thumb->getClientFilename();
$fileName = $resize_to_thumb->getClientFilename();
$fileName = 'img/bio_images/' . $fileName;
$bio->resize_to_thumb=$fileName;
$resize_to_thumb->moveTo($destination);
}
}
if ($this->Bios->save($bio)) {
$this->Flash->success(__('The bio has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The bio could not be saved. Please, try again.'));
}
$users = $this->Bios->Users->find('list', ['limit' => 200]);
$this->set(compact('bio', 'users'));
}
In my template:
<p>Add a thumb-size avatar</p>
<?php echo $this->Form->file('resize_to_thumb');?>
Best you can do is, once the upload is complete, show a thumbnail and allow the user to “change” the uploaded file. (by upload another file and replace it)
Also this allows to not upload the same file many times.
If sounds like you’re thinking that a file will be uploaded in one post, and then you create a second form from that and the file will magically be added to that post data as well? That’s not how it works. You’ll need to save the file from the first post somewhere to work with later on. (And presumably have some periodic cleanup of any such temp files that people don’t complete the process with.)
and then save it to the database on the next line:
if ($this->Bios->save($bio) && $this->Bios->save($home_page_image)) {
$this->Flash->success(__('The bio has been saved.'));
return $this->redirect(['action' => 'index']);
}
I added: if ($this->Bios->save($bio) && (isset($home_page_image)) {$this->Bios->save($home_page_image)}){
And when I submitted the form, I got the following error:
Argument 1 passed to Cake\ORM\Table::save() must implement interface Cake\Datasource\EntityInterface, instance of Laminas\Diactoros\UploadedFile given, called in C:\xampp\htdocs\pp\src\Controller\BiosController.php on line 224
Thanks dirk. The code that I submitted here was from my edit method in the controller. The add method works, it’s the edit method that doesn’t re-submit the original image. The user has to upload the image file again in the edit interface. I have a test on Wednesday morning so I am going to leave this until after the test. I have to study now.