Have to upload the image twice because the edit template doesn't show the image that was uploaded at the add page

object(App\Model\Entity\Bio) id:0 {
'id' => (int) 35
'user_id' => (int) 35
'contributor' => 'Delete doesn't work'
'resize_to_thumb' => null
'home_page_image' => 'img/bio_images/2.P12_id80604275.jpg'
'body' => '<p>delete failed</p>'
'gender' => ''
'created' => object(Cake\I18n\FrozenTime) id:1 { }
'modified' => object(Cake\I18n\FrozenTime) id:2 { }
'[new]' => false
'[accessible]' => [ ]
'[dirty]' => [ ]
'[original]' => [ ]
'[virtual]' => [ ]
'[hasErrors]' => false
'[errors]' => [ ]
'[invalid]' => [ ]
'[repository]' => 'Bios'
protected _accessible => [ ]
protected _fields => [ ]
protected _original => [ ]
protected _hidden => [ ]
protected _virtual => [ ]
protected _dirty => [ ]
protected _accessors => [ ]
protected _new => false
protected _errors => [ ]
protected _invalid => [ ]
protected _registryAlias => 'Bios'
}

So this should have worked and the link to the file “home_page_image” is saved in your database.
you can do the same with the “resize_to_thumb” .
If you want to display an already existing image in your edit form, just read here:
https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-images

No, it didn’t work. When I view the bios page, there is no image displayed after not uploading the file again in the edit method.

So maybe the problem is in the add-method or is the filename stored in your database after adding a new bio?

The problem would be in my view template not my add template. I don’t understand what you mean when you say that the problem is in my add template. Here is what I have in the view template:


<?php 

if ($bio->home_page_image != NULL){  

$image = $bio->home_page_image; 

$image = str_replace("img/", "", $image);
echo "<div class=\"recipeFloatRightLargeDiv\">";
echo $this->Html->image($image, [
    "alt" => "Website Name",
    'url' => ['controller' => 'bios', 'action' => 'index'],
    'class' => "recipeFloatRightLarge"
]); 
echo "</div>";
}

?>

This is the code for the add template:

<?php
		$session = $this->request->getSession();

		$user_id = $session->read('Auth.User.id');
?>	
<div class="row">
    <aside class="column">
        <div class="side-nav">
            <h4 class="heading"><?= __('Actions') ?></h4>
            <?php echo $this->Html->link('Cancel', ['controller' => 'users', 'action' => 'index']) ?>
        </div>
    </aside>
    <div class="column-responsive column-80">
        <div class="bios form content">
            <?= $this->Form->create($bio, ['enctype' => 'multipart/form-data']); ?>
            <fieldset>
                <legend><?= __('Add Bio') ?></legend>
                <?php
                    echo $this->Form->hidden('user_id', ['value' => $user_id]);
					echo $this->Form->control('contributor'); 
					?>
					I am 
					<?php 
					echo $this->Form->radio('gender', ['male', 'female']);
					?>
					
					<p>Add a thumb-size avatar</p> 
					<?php
					echo $this->Form->file('resize_to_thumb');?>
					<p>Add an image for your home page</p>
					<?php 
					echo $this->Form->file('home_page_image');?>
					<br style="clear: both;" />
					<div class="screenshot">
					<p>You have to select the text in order to apply formatting. See the example below:</p>
					<br />
					<img src="/img/selected.gif" />
					</div>
				<?php 
					echo $this->Form->textarea('body',['id'=>'editor']);
                ?>
            </fieldset>
            <?= $this->Form->button(__('Submit')) ?>
            <?= $this->Form->end() ?>
        </div>
    </div>
</div>

<script src="https://cdn.ckeditor.com/ckeditor5/27.1.0/classic/ckeditor.js"></script>

    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );
    </script>

It appears that the filename is being correctly saved in your database. Is that filename correct? Is the corresponding file being created in your filesystem, in the exact location you are expecting it to be?

the filename of the image in your filesystem is:

‘img/bio_images/2.P12_id80604275.jpg’

As far as I can see the image file is saved in subdirectory “bio_images” under the “img” folder.

So, when you (in your view template) remove “img/” from the filename that comes from your database to search for, CakePHP can’t find this file.

What you could do:

when saving the file (in add and edit) you should remove this line:

and then in your view template remove this:

$image = str_replace(“img/”, “”, $image);

and change

echo $this->Html->image($image, [
    "alt" => "Website Name",
    'url' => ['controller' => 'bios', 'action' => 'index'],
    'class' => "recipeFloatRightLarge"
]);

to

echo $this->Html->image('bio_images'.DS.$image, [
    "alt" => "Website Name",
    'url' => ['controller' => 'bios', 'action' => 'index'],
    'class' => "recipeFloatRightLarge"
]);

In my controller edit method, I have:

$fileName2 = $home_page_image->getClientFilename();
$destination2 = WWW_ROOT.'img'.DS.'bio_images'.DS. $fileName2;

and in the view source of my view template, I find:

img src="/img/bio_images%5C2.P12_id80604275.jpg"

Instead of a back slash between the directory bio_images and the image file name there is %5C

I googled it and found:

5C is the hex code for backward slash

Also I don’t think this is the problem because when I use the wrong image directory I should get a broken image icon instead of a blank page. Now when I change the directory path in my view template it shows me a broken image icon instead of just a blank page.

I hired a programmer to fix this so I’m not paying anyone here who has the solution as well.

I hope it works out for you makamo66.

As mentioned on several occasions I hope you can use this opportunity, and draw from their knowledge to see how it was fixed, use them as a coach or a tutor. If that isn’t possible then you may well have to resign yourself to needing to pay someone for everything you don’t understand. It would be hoped though that this programmer can debug the rest of your web app as I sense from other posts here it could be improved and you’ll learn from that.

A programmer that contacted me about the project said that if the image path was wrong, there wouldn’t necessarily be a broken image icon. He showed me some code that displayed a blank page like mine instead of a broken image icon. His code showed that he was right so I echoed the image path that was stored to the database instead of just waiting for a broken image icon to show. But even with this insight, the edit method is still faulty and the wrong image path isn’t the reason.

I’d like to quote @Zuluru

It appears that the filename is being correctly saved in your database. Is that filename correct? Is the corresponding file being created in your filesystem, in the exact location you are expecting it to be?

If you do debug($bio); in your edit template, you should be able to see the correct filename.
Then you could check in your filesystem where the file is located and with this info you will surely find a solution or post these infos and maybe we can help you finding a solution.

Thanks, dirk. This is the result of debug($bio) in my edit template:
ROOT\templates\Bios\edit.php (line 7)
object(App\Model\Entity\Bio) id:0 {
‘id’ => (int) 35
‘user_id’ => (int) 35
‘contributor’ => ‘Delete doesn’t work’
‘resize_to_thumb’ => null
‘home_page_image’ => ‘img/bio_images/2.P12_id80604275.jpg’
‘body’ => ‘

delete failed


‘gender’ => ‘’
‘created’ => object(Cake\I18n\FrozenTime) id:1 { }
‘modified’ => object(Cake\I18n\FrozenTime) id:2 { }
‘[new]’ => false
‘[accessible]’ => [ ]
‘[dirty]’ => [ ]
‘[original]’ => [ ]
‘[virtual]’ => [ ]
‘[hasErrors]’ => false
‘[errors]’ => [ ]
‘[invalid]’ => [ ]
‘[repository]’ => ‘Bios’
protected _accessible => [ ]
protected _fields => [ ]
protected _original => [ ]
protected _hidden => [ ]
protected _virtual => [ ]
protected _dirty => [ ]
protected _accessors => [ ]
protected _new => false
protected _errors => [ ]
protected _invalid => [ ]
protected _registryAlias => ‘Bios’
}
After submitting the edit form and clicking on edit again, the home_page_image is empty. This is the result of debug($bio):

‘resize_to_thumb’ => null
‘home_page_image’ => null

This thread is a mess to read through now. I’m going to try to summarize my understanding of what might be going on, let me know if this is accurate.

  1. You can upload an image successfully when adding a record.
  2. That image displays correctly when viewing that record.
  3. You then edit the record. The edit form has a spot for the image to be uploaded, but you don’t want to replace it so you leave that empty.
  4. The image is deleted.

Yes, Zuluru, that is correct. I thought the problem was that I had auto-increment enabled in my Bios table. I’m not using it anymore when I create a Bios id. Instead I’m setting the Bios id equal to the user id. I turned it off but the problem persists.

You need to do one of two things:

  1. Don’t include the image field on the edit page, but instead have a separate form for updating just that.
  2. Add logic in your edit action to skip updating the image if a new one wasn’t provided.

Thanks for the suggestions, Zuluru.

I found a programmer to fix it for me. I’m pasting in his code in the next reply

public function edit($id = null)
    {
$bio = $this->Bios->get($id, [
            'contain' => [],
        ]);
error_log("Bio before patch: " . print_r($bio,true));
//keep a reference to the original images
$thumb = $bio['resize_to_thumb'];
$hpimg = $bio['home_page_image'];
        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'))) {
 if($this->request->getData('resize_to_thumb')['size'] > 0){
     $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);
              }
   
          } else {
//a new image wasn't uploaded. Preserve what we had before
$bio->resize_to_thumb = $thumb;
 }
   
 if($this->request->getData('home_page_image')['size'] > 0){
  $home_page_image = $this->request->getUploadedFile('home_page_image');

              if ($home_page_image->getError() == 0) {

$fileName2 = $home_page_image->getClientFilename();
   $destination2 = WWW_ROOT.'img'.DS.'bio_images'.DS.$fileName2;
$fileName2 = 'img/bio_images/' . $fileName2;
$bio->home_page_image=$fileName2;
                $home_page_image->moveTo($destination2);
 }
          } else {
 //a new image wasn't uploaded. Preserve what we had before.
 $bio->home_page_image = $hpimg;
 }
        }

            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'));
    }