Symfony 3 File Upload In Edit Form
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_cla
Solution 1:
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(),
));
}
Post a Comment for "Symfony 3 File Upload In Edit Form"