Friends,
I’m trying to edit a form with the upload field not required, that is, keeping the images that have been added.
I’m adding the images like this:
.
.
$product = $this->Products->newEntity();
if ($this->request->is('post')) {
if(!empty($this->request->data['img_product']['name'])){
$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->Product->patchEntity($produto, $this->request->getData());
if ($this->Products->save($product)) {
$this->Flash->success(__('Produto salvo com sucesso!'));
return $this->setAction('index');
}
$this->Flash->success(__('error!'));
}
if(empty($this->request->data['img_product']['name'])){
$this->request->data['img_product'] = "sem-imagem.jpg";
$product->path = "img/img_products/";
$product = $this->Produtos->patchEntity($produto, $this->request->getData());
if ($this->Products->save($product)) {
$this->Flash->success(__('save'));
return $this->setAction('index');
}
}
}
.
.
This works perfectly.
However, I want to edit this form without the need for the file field to be mandatory, that is, the image that was previously registered can be kept.
the products table has the img_product and path fields to save the image path.
The method of editing is as follows:
$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_product);
$filename = $this->request->data['img_product']['name'];
$myext = substr(strchr($filename, "."), 1);
$path = "img/img_products/".Security::hash($filename).".".$myext;
$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;
}
$produto = $this->Products->patchEntity($produto, $this->request->getData());
if ($this->Products->save($produto)) {
$this->Flash->success(__('save'));
return $this->setAction('index');
}
}
$this->Flash->success(__('error'));
}
edit.ctp
<small>Image</small>
<?= $this->Form->control('img_product', [
'class' => 'form-control form-control-user',
'type' => 'file',
'allowempty' => true,
'label' => false,
]);?>
ProductTable.php
$validator
->scalar('img_product')
->maxLength('img_product', 255)
->allowEmptyString('img_product');
$validator
->scalar('path')
->maxLength('path', 255)
->notEmptyString('path');
When the image field is not empty, the image is replaced normally. But I’m having trouble maintaining the image. If a new image is not inserted. I appreciate any comments.
The basic idea is to keep a previously registered image.