Symfony CollectionType:合并新条目



我的symfony表单代表一个实体 Mail,它与另一个称为 Attachment的实体有一对多关系。因此,MailType表单包含用于嵌入其AttachmentType表格的CollectionType字段:

$builder
    ->add('attachments', CollectionType::class, [
        'entry_type' => AttachmentType::class,
        'allow_add' => true,
        'allow_delete' => false,
        'by_reference' => false,
    ]);

我的观点只会向我的Symfony Backend发送新的附件。因此,当将表单数据存储到数据库中时,我只想添加邮件的新附件而不触摸任何现有附件。

不幸的是,Symfony/Doctrine的行为不同:如果n附件包含在表单数据中,则n首先现有附件被这些新附件覆盖:

existing attachments (in DB): [old1, old2, old3]
new attachments (contained by HTTP request): [new1, new2]
desired result in DB: [old1, old2, old3, new1, new2]
actual result in DB: [new1, new2, old3]

我该如何实现?我认为by_reference => false会导致addAttachment方法被调用,所以我也希望这可以在框外工作。

我的Mail实体代码:

class Mail {
    /**
     * @ORMOneToMany(targetEntity="AppBundleEntityAttachment", mappedBy="mail", cascade={"persist", "remove"})
     */
    protected $attachments;
    ...
    public function addAttachment(AppBundleEntityttachment $attachment) {
        $attachment->setMail($this);
        $this->attachments[] = $attachment;
        return $this;
    }
}

我的控制器代码处理表格:

    // $mail = find mail in database
    $form = $this->createForm(MailType::class, $mail);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $mail = $form->getData();
        $em = $this->getDoctrine()->getManager();
        $em->persist($mail);
        $em->flush();
    }

有几种方法可以做您想做的事情。最简单的是将空数据或新附件实体提供给您的表单字段:

$builder
        ->add('attachments', CollectionType::class, [
            'entry_type' => AttachmentType::class,
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
            'data' => [new Attachment()] // or add more or []
        ]);

然后在您的邮件实体中:

public function addAttachment(Attachment $attachment) {
    $attachment->setMail($this);
    $this->attachments[] = $attachment;
    return $this;
}
public function removeAttachment(Attachment $attachment) {
    return $this;
}

如果您正在使用 removeAtTachment 用于其他功能,并且您想实际删除附件,则可以利用表单字段的 property_path 设置:

'property_path' => 'appendAttachments'

并创建 AddAppendAttachment removeAppendAttachment

public function addAppendAttachment(Attachment $attachment) {
    $attachment->setMail($this);
    $this->attachments[] = $attachment;
    return $this;
}
public function removeAppendAttachment(Attachment $attachment) {
    return $this;
}

最新更新