【发布时间】:2018-09-05 11:53:45
【问题描述】:
你好(对不起,我的英语不太自信)
我实际上正在开发一个显示眼镜信息的 Symfony 网站。 现在,我需要在创建其中一个时添加一个图像。在 this 教程的帮助下,我设法做到了。
它基本上是这样工作的:我将图像上传到站点目录,然后将文件名发送到实体(存储在 MySQL 数据库中)。然后我可以在眼镜的细节中显示图像。
当我想编辑景观时出现问题。我无法更新图像的名称。我只有两种可能:1/不编辑实体,或 2/更改图像名称,然后随机获取一个我无法再显示的图像 (这些名称通常类似于 /tmp/ phpWb8kwV)
我的图像在实体 (在 Spectacle.php 中) 中是这样实例化的:
/**
* @var string
*
* @ORM\Column(name="image", type="string", length=255)
* @Assert\NotBlank(message="Veuillez ajouter une image à votre spectacle.")
* @Assert\File(mimeTypes={ "image/png" })
*/
private $image;
眼镜形式的FormType是这样(在SpectacleType.php中):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image',FileType::class, array(
'label' => 'Image du spectacle',
'required' => false, //(Still need to provide a file to finalize the creation/edit)
));
}
访问此页面的控制器是这样制作的(在 SpectacleController.php 中):
/**
* Creates a new spectacle entity.
*
* @Route("/new", name="admin_spectacle_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$spectacle = new Spectacle();
$form = $this->createForm('FabopBundle\Form\SpectacleType', $spectacle);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
$em->persist($spectacle);
$em->flush();
return $this->redirectToRoute('admin_spectacle_show', array('id' => $spectacle->getId()));
}
return $this->render('spectacle/new.html.twig', array(
'spectacle' => $spectacle,
'form' => $form->createView(),
));
}
路由到编辑视图的功能大致相同,但我不能使用
$spectacle->setImage($fileName);
解决这个问题有两种可能性:我希望能够更新实体中的新文件名(使用其他信息)或能够在不更改文件名的情况下更新实体。
我希望我能清楚地解释我的问题... 提前感谢您的回复。
【问题讨论】:
标签: php symfony upload doctrine symfony-3.4