首页 > 解决方案 > 带有 VichUploader 和一对多关联实体的 Symfony 上传

问题描述

这是我的问题简介:我有 2 个关联 OneToMany 关系的实体。第一次上传没有问题,但更新过程很混乱。如果发送更新请求,则Form的handleRequest函数会删除一些关系实体并添加新的上传文件。

例如:我有 1 个学分和 2 个与该学分相关的额外文件。然后当我想更新和上传任何其他文件时。执行Form的handleRequest函数时,最后一个文件已被自动删除。

这是我的代码库:

信用实体:

/**
 * @ORM\Entity(repositoryClass="App\Repository\CreditRepository")
 * @Vich\Uploadable()
 */
class Credit
{

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ExtraFile", mappedBy="credit", cascade={"persist", "remove"})
     * @var ExtraFile[] An ArrayCollection of ExtraFile objects.
     */
    private $extraFiles;

ExtraFile实体:

/**
 * Class ExtraFile
 * @ORM\Entity()
 * @Vich\Uploadable()
 */
class ExtraFile
{

    /**
     * @ORM\ManyToOne(targetEntity="Credit", inversedBy="extraFiles")
     */
    private $credit;

在我的控制器中:

public function applicationFiles(Credit $credit, Request $request): Response
{
    $form = $this->createForm(CreditExtraType::class, $credit);
    $form->handleRequest($request); // <--- At this point the $credit entity "extraFiles" entities changed and removed the last or two entities (it depent how much file send for upload) with OneToMany.
    if ($form->isSubmitted() && $form->isValid()) {

CreditExtraType代码

class CreditExtraType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('extraFiles', CollectionType::class, [
                'entry_type' => CreditExtraVichFileType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'required' => false,
                'by_reference' => false,
                'disabled' => false,
            ])
        ;

    }

你有什么主意吗?

标签: symfonysymfony4symfony-formsvichuploaderbundle

解决方案


推荐阅读