File upload on edit scenario

Hi. This snippet of codes supposed to check if the controller method is edit. And then check if the image (which is an input type file) comes with a file.
If so the old image will be deleted before uploading the new one. When the input has value everything works except deleting old image. But if it empty this error occurs.

Isn’t $entity->has('image') going to return true in the case where there was an image originally but nothing was submitted in the edit?

“The has() method will return true if a field is defined and has a non-null value. You can use isEmpty() and hasValue() to check if a field contains a ‘non-empty’ value”.

:point_up_2: That’s from the docks I also tried hasValue(), isEmpty() and PHP built-in function empty() but still get the same result.

Thinking about what you stated there. If CakePHP checks the DB to determine whether image has value or not that’s maybe the case. Since there’s no field in the table with that name.

I’m only save the file name there in a field named img_name & move the file to IMG folder.

If image isn’t a real field in the database, it’s probably useful to show us the code relevant code that could lead to it being set in the entity. Maybe the issue lies there, not in the code you’ve shared so far. And/or show the output from debug($entity->image) at the point where you’ve checked that this property exists.

The first pic is when requesting ‘users/edit/$id’
And there’s no image property since it doesn’t exist in the table.

The second pic when submitting the form without selecting a file, and this is when the error occurs.

The third pic when submitting the form with a file and that works as expected.

I’m handling these in UsersTable not in UsersController.

So, it’s clear from the second one that there is an image property in the entity, but it’s got a null stream and file name, and a non-zero error code. So $entity->has('image') is going to be true in your code, because there’s an object there, but the object is not what you’re expecting. You’ll need something like

if ($entity->has('image') && $entity->image->getError() === UPLOAD_ERR_OK)

OK I’ll try that. Thanks.