Symfony - ArrayColletion 中的项被删除,但仍显示在列表中



我有BudgetBudgetItemProduct实体。Budget有一个BudgetItem列表,该列表具有一个或多个Products。我正在尝试按照本教程删除这些以前添加的产品的列表。当我尝试从BudgetItem列表中删除现有Product时,我可以看到我的Budget的总价格减少了我删除的特定Product的总金额,但它没有从列表中删除,在Budget实体中。

首先,让我告诉你他们的关系:

Budget

/**
 * @var integer
 * 
 * @ORMOneToMany(targetEntity="BudgetItem", mappedBy="budget", cascade={"persist"}, orphanRemoval=true)
 */
private $items;

BudgetItem

/**
 * @ORMManyToOne(targetEntity="Product")
 * @ORMJoinColumn(nullable=false)
 */
private $product;
/**
 * @ORMManyToOne(targetEntity="Budget", inversedBy="items")
 * @ORMJoinColumn(nullable=false)
 */
private $budget;

现在,我的BudgetController editAction,根据文档进行操作:

public function editAction($id, Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $budget = $em->getRepository('CDGBundle:Budget')->find($id);
    $products = new ArrayCollection();
    foreach ($budget->getItems() as $item) {
        $products->add($item);
    }
    $form = $this->createForm(BudgetType::class, $budget);
    $form->handleRequest($request);
    if ($form->isValid()) {
        if ($this->get('cdg.budget_updater')->updateProductQtd($budget)) {
            // Here /
            foreach ($products as $product) {
                if (!$budget->getItems()->contains($product)) {
                    $product->getBudget()->removeItem($product);
                    $em->persist($product);
                }
            }
            // Here /
            $this->get('cdg.budget_updater')->updatePaymentDates($budget);
            $this->addFlash('notice', 'Orçamento de '' . $budget->getCustomer() . '' alterado com sucesso');
        } else {
            $this->addFlash('notice', 'Material(is) esgotado(s). Reveja o seu estoque.');
        }
        return $this->redirectToRoute('budgets');
    }
    return $this->render('budget/edit.html.twig', array(
        'form' => $form->createView(),
        'title' => 'Editar orçamento de ' . $budget->getCustomer()
    ));
}

我不得不从方法内部删除foreach循环updateProductQtd()并在循环后添加$em->flush(),正如@Artamiel所说:

if ($form->isValid()) {
    foreach ($products as $product) {
        if (!$budget->getItems()->contains($product)) {
            $product->getBudget()->removeItem($product);
            $em->persist($product);
        }
    }
    $em->flush();
    if ($this->get('cdg.budget_updater')->updateProductQtd($budget)) {
        $this->get('cdg.budget_updater')->updatePaymentDates($budget);
        $this->addFlash('notice', 'Orçamento de '' . $budget->getCustomer() . '' alterado com sucesso');
    } else {
        $this->addFlash('notice', 'Material(is) esgotado(s). Reveja o seu estoque.');
    }
    return $this->redirectToRoute('budgets');
}

相关内容

  • 没有找到相关文章

最新更新