gpt4 book ai didi

forms - Symfony CollectionType : Merge new entries

转载 作者:行者123 更新时间:2023-12-02 09:41:27 27 4
gpt4 key购买 nike

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

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

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

不幸的是,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 {
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Attachment", mappedBy="mail", cascade={"persist", "remove"})
*/
protected $attachments;

...

public function addAttachment(\AppBundle\Entity\ttachment $attachment) {
$attachment->setMail($this);
$this->attachments[] = $attachment;
return $this;
}
}

我的 Controller 代码处理表单:

    // $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'

并创建addAppendAttachmentremoveAppendAttachment:

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

public function removeAppendAttachment(Attachment $attachment) {
return $this;
}

关于forms - Symfony CollectionType : Merge new entries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47829368/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com