Todo lo manejo desde la Entidad "UpFile"
Código PHP:
...
use SymfonyComponentValidatorConstraints as Assert;
use SymfonyComponentHttpFoundationFileFile;
/**
* UpFile
*
* @ORM\Table(name="UpFile")
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class UpFile
{
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $path;
/**
* @Assert\Image(
* maxSize="100k"
.....
* )
*/
protected $file;
/**
* @var \RCV
*
* @ORM\ManyToOne(targetEntity="RCV", inversedBy="Ilustrarxy", cascade={"persist"})
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="Id_RCV", referencedColumnName="Id")
* })
*/
private $IdRCV;
private $temp;
/**
* @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);
}
/**
* @ORM\PreRemove()
*/
public function storeFilenameForRemove()
{
$this->temp = $this->getAbsolutePath();
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if (isset($this->temp)) {
unlink($this->temp);
}
}
/**
* Sets file.
*
* @param File $file
*/
public function setFile(File $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';
}
}
/**
* Get file.
*
* @return File
*/
public function getFile()
{
return $this->file;
}
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir().'/'.$this->Id.'.'.$this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir().'/'.$this->path;
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
return 'file/Ilustraciones';
}
// Todos los SETy GET
....
}
En el controlador lo pongo asi
Código PHP:
$Cuento=new RCV();
// La entidad "UpFile" es uno o varios <input type="file"> embebidos en RCV()
$Cuento->addIlustrarxy(new UpFile());
$form= $this->createForm(new CuentoType(), $Cuento);
$form->handleRequest($request);
if ($form->isValid()){
$em = $this->getDoctrine()->getManager();
$Cuento->setIdUser($this->getUser());
$em->persist($Cuento);
$em->flush();
....
}
...