symfony 3 file upload in edit form

2019-08-19 23:11发布

i have an entity "Cours" with a field "image".
this is the builder of CoursType.php

$builder
        ->add('titre')
        ->add('image', FileType::class, array('data_class' => null, 'label'=>false,'required'=>false))                                                                                       
        ->add('videoIntro')
            );

The problem is in the ""edit form"" when i submit this form without uploading new image, a null value will be passed to "image".

this is controller code of editAction

public function editAction(Request $request, Cours $cour)
{   
    $em = $this->getDoctrine()->getManager();

    $deleteForm = $this->createDeleteForm($cour);


    $editForm = $this->createForm('LearnBundle\Form\CoursType', $cour);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid())
    {

        $image=$cour->getImage();
        $imageName = md5(uniqid()).'.'.$image->guessExtension();
        $image->move($this->getParameter('images_directory'),$imageName);
        $cour->setImage($imageName);

        $em->flush();

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

    return $this->render('cours/edit.html.twig', array(
        'cour' => $cour,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),

    ));
}

1条回答
时光不老,我们不散
2楼-- · 2019-08-19 23:37

Should be something like this:

public function editAction(Request $request, Cours $cour) {
    //fetch current img is exists
    $img=$cour->getImage();
    if($img !== null) {
        $cour->setImage(new File($this->getParameter('images_directory').$img);
    }

    $em = $this->getDoctrine()->getManager();
    $deleteForm = $this->createDeleteForm($cour);
    $editForm = $this->createForm('LearnBundle\Form\CoursType', $cour);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {
        //Check if new image was uploaded
        if($cour->getImage() !== null) {
            //Type hint
            /** @var Symfony\Component\HttpFoundation\File\UploadedFile $newImage*/
            $newImage=$cour->getImage();
            $newImageName= md5(uniqid()).'.'.$file->guessExtension();
            $newImage->move($this->getParameter('images_directory'), $newImageName);
            $cour->setImage($newImageName);
        } else {
            //Restore old file name
            $cour->setImage($img);
        }

        $em->flush();

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

    return $this->render('cours/edit.html.twig', array(
        'cour' => $cour,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),

    ));
}
查看更多
登录 后发表回答