Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files from a folder in Symfony 3

I have a controller with a createAction an editAction and a deleteAction.

I can add pictures and delete them from the database.

As I followed the Symfony doc to create an uploader file, I also created in my config.yml this route

parameters:
   uploaded_restaurants: "%kernel.root_dir%/../web/uploads/restaurants"

so this is the routes for my uploaded files.

My problem

When I delete my pictures with my delete action, its fine it deletes it in my database. But not in my folder /web/uploads/restaurants I tried to find a way to be able to delete them in my folder too, but couldn't succeed it.

I tried also with a Filesystem() to remove them, but I've must have written it badly.

Here is my controller:

    class MediaController extends Controller
{
    /**
     * @param Request $request
     * @param Restaurant $restaurant
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function newAction(Request $request, Restaurant $restaurant)
    {
        $media = new Media();
        $form = $this->createForm(MediaType\CreateType::class, $media);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $mediaList = $this->getDoctrine()->getRepository('AppBundle:Media')->findImageByRestaurantType($restaurant, $form->get('context')->getData());

            if ($mediaList == null || count($mediaList) < 1) {
                $media->setType('img')
                    ->setContext($form->get('context')->getData())
                    ;
            } else {
                $media = $mediaList;
            }

            $imageFile = $request->files->get('create')['name'];
            $targetDir = $this->getParameter('uploaded_restaurants');
            $imageName = $this->get('app.uploader')->upload($imageFile, $targetDir);

            /** @var  $originalName */
            $originalName = $imageFile->getClientOriginalName();
            $media->setName($imageName)
                ->setOriginalName($originalName)
                ->setCreatedAt(new \DateTime());

            $em = $this->getDoctrine()->getManager();
            $media->setRestaurant($restaurant);
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('admin_restaurant_show_fr', array('id' => $restaurant->getId()));
        }
        return $this->render('admin/restaurant/media/new.html.twig', array(
            'restaurant' => $restaurant,
            'form' => $form->createView()
        ));
    }

    /**
     * @param Request $request
     * @param Media $media
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request, Media $media)
    {
        $em = $this->getDoctrine()->getManager();

        $editForm = $this->createForm(MediaType\EditType::class, $media);
        $editForm->handleRequest($request);
        $restaurant = $media->getRestaurant();

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $imageFile = $request->files->get('edit')['name'];
            $targetDir = $this->getParameter('uploaded_restaurants');
            $imageName = $this->get('app.uploader')->upload($imageFile, $targetDir);

            if ($request->files->get('edit')['name'] != null) {

                $fs = new Filesystem();
                try {
                    $fs->remove($this->get('kernel')->getRootDir() . '/../web/uploads/restaurants' . $media->getName());
                } catch (IOException $e) {
                    echo "error";
                }

                /** @var $originalName */
                $originalName = $imageFile->getClientOriginalName();
                $media->setName($imageName)
                    ->setOriginalName($originalName)
                    ->setUpdatedAt(new \DateTime());
            }
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('admin_restaurant_show_fr', array('id' => $restaurant->getId()));
        }
        return $this->render('admin/restaurant/media/edit.html.twig', array(
            'media' => $media,
            'restaurant' => $restaurant,
            'editForm' => $editForm->createView()
        ));
    }

    /**
     * @param Media $media
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Media $media)
    {
        $restaurant = $media->getRestaurant();
        $em = $this->getDoctrine()->getManager();
        $em->remove($media);
        $em->flush();

        return $this->redirectToRoute('admin_restaurant_show_fr', array('id' => $restaurant->getId()));
    }
}

As you can see in the editAction I tried to add a Filesystem in order to remove the file

my question

How can I do that for my editAction and my deleteAction in order to delete properly my files from the directory? If you don't really understand my code, is there an example you can show me that works? Thank you

like image 210
chicken burger Avatar asked Mar 20 '17 14:03

chicken burger


1 Answers

Both when editing or deleting a media you have the existing object with it's filename available, e.g.:

public function deleteAction(Media $media){ ... }

Doctrine will read the id from the url and load the corresponding media from database. You can use this object to get the old image location and then remove that image.

// getName() will contain the complete filename with path.
// Check your showAction where you call `setName($imageName)`
$filename = $media->getName();

$filesystem = new Filesystem();
$filesystem->remove($filename);

You can do the same in your editAction instead of the code you provided.

like image 71
dbrumann Avatar answered Sep 22 '22 07:09

dbrumann