fileTypeフィールドを持つエンティティのコレクションがある場合、フォームの更新を正しく処理する方法。私は Symfony upload docsに従って行動とリスナーを行いました。エンティティの作成は完璧に機能しますが、ファイルが選択されていないため、編集アクションは失敗し、symfonyはコレクションフィールドをファイルフィールドにnull値で更新しようとします。symfony 3フォームコレクションエンティティfiletypeフィールドeditAction
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()]);
}
}
// ...
私はどこかの空のファイルのフィールドの設定を解除する必要がありますが、私がどこかわからない...(
PS VichUploaderBundle
のようなバンドルを使うことができることは知っていますが、どのように動作するのか、そして私がwronをやっていることを理解したいと思いますg! P.P.S.私の英語には申し訳ありません
私はこのような何かについて考えを解決しますが、 'FormEvents :: PRE_SET_DATA'イベントリスナーを持ちます。元のオブジェクトを取得し、提出されたフィールドを確認する可能性があります。詳細については、[docs](https://symfony.com/doc/current/form/dynamic_form_modification.html) – Vladimir
のリンクをご覧ください。私はあなたが絶対に正しいと思います。 FormEventsも同様に使用できます。 – Mz1907