我有一个Post实体,其Cover字段包含一个实体-图片
//src/Entity/Post.php
/**
* @var Image
* @ORM\ManyToOne(targetEntity="Image", cascade={"persist"})
* @ORM\JoinColumn(name="cover_id", referencedColumnName="id")
**/
private $cover;
当我使用简单的功能(Symfony自动创建它,然后使用CRUD进行发布)编辑Post时:
//src/Controller/PostController.php
/**
* @Route("/{id}/edit", name="post_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Post $post): Response
{
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('post_index');
}
return $this->render('post/edit.html.twig', [
'post' => $post,
'form' => $form->createView(),
]);
}
和形式
//src/Form/PostType.php
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cover', ImageType::class, array(
'label' => 'Cover'
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Post::class
]);
}
}
//src/Form/ImagetType.php
class ImageType extends FileType
{
private $imagePath;
/**
* ImageType constructor.
* @param $imagePath
*/
public function __construct($imagePath)
{
$this->imagePath = $imagePath;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->addModelTransformer(new CallbackTransformer(
function(Image $image = null) {
if ($image instanceof Image) {
return new File($this->imagePath . '/' . $image->getFile());
}
},
function(UploadedFile $uploadedFile = null) {
if ($uploadedFile instanceof UploadedFile) {
$image = new Image();
$image->setFile($uploadedFile);
return $image;
}
}
));
}
public function getBlockPrefix()
{
return 'image';
}
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'required' => false
]);
}
}
提交编辑表单后,封面字段(即使填充了一个对象)也会显示为空白。
>如何在编辑Post实体的其他字段时使封面上有东西保存?P.S。 我使用此示例下载图像-https://github.com/cirykpopeye/easy-image-uploading-with-symfony-4/tree/master/app
我尝试使用此https://symfony.com/doc/current/doctrine.html#persisting-objects-to-the-database 但这并不能帮助我正确保存
答案 0 :(得分:0)
您应该对保存代码进行少量更改。
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($post); // Make persist (prepare you're entity to save in db
$em->flush(); // Save prepared entity to database
return $this->redirectToRoute('post_index');
}
一些有用的链接: