I'm trying to upload a file to my application by following the instructions in the documentation of Symfony Using the id as the filename. But nothing happens when there is a previously uploaded file.
My form contains a field File only, which is associated with the entityDocument as described in Basic Setup, with the only difference that do not define the $name property.
My entity definition:
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Document
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* @Assert\File()
*/
private $file;
}
My form definition (within sonata admin class):
/**
* @param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper->add('file');
}
When the document is new, the file is uploaded correctly. But then if I try to upload another to replace the previous file then it does nothing and the old file still exists.
The critical zone it's (Using the id as the filename):
use Symfony\Component\HttpFoundation\File\UploadedFile;
// ...
class Document
{
// ...
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (is_file($this->getAbsolutePath())) {
// store the old name to delete after the update
$this->temp = $this->getAbsolutePath();
} else {
$this->path = 'initial';
}
}
// ...
}
The second time, when I try to change the previously uploaded file, these methods are not executed (Using the id as the filename):
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Document
{
// ...
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
$this->path = $this->getFile()->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->temp);
// clear the temp image path
$this->temp = null;
}
// you must throw an exception here if the file cannot be moved
// so that the entity is not persisted to the database
// which the UploadedFile move() method does
$this->getFile()->move(
$this->getUploadRootDir(),
$this->id.'.'.$this->getFile()->guessExtension()
);
$this->setFile(null);
}
}
Anyone can tell me that I may be doing wrong?