Friends, I have a form with a file field to add photos of products. If it is necessary to edit, I need to keep the photo that was registered at the first moment. I have this method for editing:
public function edit($slug = null)
{
$product = $this->Products->findBySlug($slug)->firstOrFail();
if ($this->request->is('post') || $this->request->is('put')) {
if(!empty($this->request->data['img_product']['name'])){
unlink(WWW_ROOT .$product->path.$product->img_produto);
$filename = $this->request->data['img_product']['name'];
$myext = substr(strchr($filename, "."), 1);
$path = "img/img_products/".Security::hash($filename);
$uploadFile = $path.$filename;
if(move_uploaded_file($this->request->data['img_product']['tmp_name'], $uploadFile))
{
$this->request->data['img_product'] = $filename;
$this->request->data['path'] = $path;
}
}
$product = $this->Products->patchEntity($product, $this->request->getData());
if ($this->Products->save($product)) {
$this->Flash->success(__('Save'));
return $this->setAction('index');
}
}
.
.
When I choose an image, it goes to the folder. But when I don’t choose, the img_product information is deleted from the database, and the path continues.
My question is to keep the img_product, just as it is done in the image path
My edit.ctp
<div class="form-group row">
<div class="col-sm-12 mb-3 mb-sm-0">
<small>Image</small>
<?= $this->Form->control('img_product', [
'class' => 'form-control form-input',
'type' => 'file',
'label' => false,
]);?>
</div>
</div>
ProductTable.php
$validator
->scalar('img_product')
->maxLength('img_product', 255)
->allowEmptyString('img_product');
$validator
->scalar('path')
->maxLength('path', 255)
->allowEmptyString('path');
I appreciate any comments.