以编辑形式上传symfony 3文件 [英] symfony 3 file upload in edit form
本文介绍了以编辑形式上传symfony 3文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实体"Cours",其字段为"image".
这是CoursType.php的构建器
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".
这是editAction的控制器代码
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(),
));
}
推荐答案
应该是这样的:
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(),
));
}
这篇关于以编辑形式上传symfony 3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文