【发布时间】:2021-12-17 07:10:03
【问题描述】:
在此处遵循官方 Symfony 文档时,我无法使我的逻辑工作:https://symfony.com/doc/current/form/form_collections.html#allowing-tags-to-be-removed
基于示例,我需要获取 originalTags,然后在处理完表单后将它们与新标签进行比较。
在我的例子中,我有一个 Purchase 实体,它可以有一个 PurchaseProducts(ManyToMany) 的集合。就我而言,当我更改 PurchaseProduct 时,我需要更新已删除的购买库存。但是,无论我如何获得原始 PurchaseProducts,在 $form->handleRequest() 之后,它们都会使用新值进行更新,并且我会丢失有关原始值的任何信息。
片段构成我的控制器的逻辑:
/** @var Purchase $purchase */
$purchase = $this->getDoctrine()
->getRepository(Purchase::class)
->find($id);
if (!$purchase) {
$this->addFlash('error', 'Purchase not found');
return $this->redirect($this->generateUrl('purchase_list'));
}
$originalProducts = new ArrayCollection();
foreach ($purchase->getPurchaseProducts() as $purchaseProduct) {
$originalProducts->add($purchaseProduct);
}
$form = $this->createForm(PurchaseType::class, $purchase);
if ($request->isMethod('POST')) {
dump($originalProducts); // Original entities are here
$form->handleRequest($request);
dump($originalProducts);die; // Original entities are updated with the new ones
...
// This will not work since originalProducts already has the new entities
foreach ($originalProducts as $purchaseProduct) {
if (false === $purchase->getPurchaseProducts()->contains($purchaseProduct)) {
// update stock here
}
}
我尝试了很多选项,比如克隆、查询数据库等等,但是在 handleRequest 之后我总是得到相同的更新实体。为什么?
【问题讨论】:
-
我认为您应该在将 purchaseProduct 添加到您的 ArrayCollection() 之前尝试序列化它
标签: forms symfony doctrine symfony5