у меня есть сущность "Cours" с полем "image" .
это конструктор CoursType.php
$builder
->add('titre')
->add('image', FileType::class, array('data_class' => null, 'label'=>false,'required'=>false))
->add('videoIntro')
);
Проблема заключается в «форме редактирования», когда я отправляю эту форму без загрузки нового изображения, в «изображение» будет передано нулевое значение.
это код контроллера 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(),
));
}
Ошибка: вызов функции-члена guessExtension () в строке именно в этой строке «$ imageName = md5 (uniqid ()). '.'. $ Image-> guessExtension ();»
@FaroukDouglas Отредактировал, забыл добавить подсказку типа ...;)
я имею в виду, какие изменения я должен сделать в этой строке "$ imageName = md5 (uniqid ()). '.'. $ image-> guessExtension ();"
Ах, извините, забыл удалить ваш код ... Опять обновился ...;)
Поэтому вам нужно проверить, действительно ли изображение установлено пользователем, перед обработкой, как если бы оно было отправлено.