Reputation: 59
I just created an action that delete a record of an entity from my db. The action is:
public function eliminaricettaAction($id)
{
$em = $this->getDoctrine()->getManager();
$ricetta = $em->getRepository('AppBundle:Ricette')->find($id);
$em->remove($ricetta);
$em->flush();
return $this->render('adminarea/gestionericette.html.twig', array(
'base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'),
));
}
And the error I get is:
Warning: unlink(): No such file or directory
So I think the problem is in the entity it self, in particular in this peace of code:
/**
* @ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
What I'm doing wrong?
Upvotes: 0
Views: 464
Reputation: 5668
You are attempting to delete a file that does not exist.
Before attempting to delete files, you should make sure they exist. Confirm that you actually get a file path back from $this->getFullImagePath()
, and that the file at the path exists by using file_exists().
You could implement it like this:
public function removeImage()
{
if($file = $this->getFullImagePath() && file_exists($file)) {
unlink($file);
rmdir($this->getUploadRootDir());
}
}
Ideally, you would also check that $this->getUploadRootDir()
returns a value and that the directory exists and is not empty before attempting to remove it; but you might also consider whether or not it's actually necessary to remove the uploadRootDir
each time a file is deleted. (Whether you should or not is a separate question entirely.)
Upvotes: 4
Reputation: 830
First, you should check that the file exists, and @jbafford's answer is good about this.
But next you must check that the uploadRootDir
is not empty because you can't remove a directory that is not empty.
$scannedDir = $this->getUploadRootDir();
if (is_dir($scannedDir)) {
$entries = scandir($entries);
if (count($entries) === 2) {
// When you have 2 entries it means you have "." and ".."
rmdir($scannedDir);
} else {
// Directory is not empty, so take care about this.
}
} else {
// Directory does not exist so you may throw an exception or do something else.
}
Upvotes: 0