如何正确处理表单更新,当实体集合中有fileType字段时。 我根据Symfony上传文档进行了操作和侦听器。实体创建完美运行,但编辑操作失败,因为没有选择文件,而Symfony尝试在文件字段上更新集合实体的空值。
AppBundle\Entity\Product:
type: entity
# ...
oneToMany:
images:
targetEntity: Image
mappedBy: product
表单:
// AppBundle\Form\ProductType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add(
'images',
CollectionType::class,
[
'entry_type' => ImageType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'entry_options' => ['label' => false],
'label_attr' => [
'data-feature' => 'editable',
],
]
);
}
// AppBundle\Form\ImageType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class, ['required' => false])
// another fields...
}
动作:
// AppBundle\Controller\Backend\ProductController
// ...
public function editAction(Request $request, EntityManagerInterface $em, Product $product)
{
$editForm = $this->createForm('AppBundle\Form\ProductType', $product);
$editForm->handleRequest($request);
$originalImages = new ArrayCollection();
foreach ($product->getImages() as $image) {
$originalImages->add($image);
}
if ($editForm->isSubmitted()) {
if ($editForm->isValid()) {
foreach ($originalImages as $image) {
if (false === $product->getImages()->contains($image)) {
$em->remove($image);
}
}
$em->flush();
$this->addFlash('success', 'Success');
} else {
$this->addFlash('warning', 'Error saving');
}
return $this->redirectToRoute('backend_product_edit', ['id' => $product->getId()]);
}
}
// ...
我认为我需要在某个地方取消设置空文件字段,但我不知道在哪里...
P.S. 我知道我可以使用像VichUploaderBundle
这样的捆绑包,但我想要了解它是如何工作的,以及我做错了什么!
P.P.S. 抱歉我的英语不好。
FormEvents::PRE_SET_DATA
事件监听器。有可能获取原始对象并检查提交的字段,在文档中有更多信息。 - sadikoff