I’m reading and trying to apply this article about File Uploads, but there is a problem. It’s said that this:
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$document->upload();
$em->persist($document);
$em->flush();
$this->redirect(...);
}
should go in a Controller and here is the definition of the upload function
public function upload()
{
// the file property can be empty if the field is not required
if (null === $this->file) {
return;
}
// we use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the target filename to move to
$this->file->move($this->getUploadRootDir(), $this->file->getClientOriginalName());
// set the path property to the filename where you'ved saved the file
$this->path = $this->file->getClientOriginalName();
// clean up the file property as you won't need it anymore
$this->file = null;
}
But where should I put this? I tried in the controller, above the action which calls it and an error occures – Fatal error: Call to undefined method... I also tried to put it in a different class and file and to add its namespace with use, but the error stays.
Could you please show me where is the mistake? 🙂
If you look carefully at the code, you will see that upload is called as a function of the document object:
So, that is where it should go, in your Document entity class