我正在使用Symfony 3.x和Doctrine。我有一个与QuoteItem实体关联的集合实体quoteItemAdditionalWork。我有另一个名为WorkOrder的实体。 WorkOrder实体是WorkOrderType表单的指定data_class。在WorkOrderType表单上,我需要包括QuoteItem实体中的表单元素作为未映射的表单字段(每个表单类型-symfony规则一个data_class)。表单集合quoteItemAdditionalWork是WorkOrderType表单中包含的表单字段之一,由于quoteItemAdditionalWork与WorkOrder没有实体关联,因此在表单上没有映射。
public function buildForm (FormBuilderInterface $builder, array $options)
{
$builder->add('quoteItemAdditionalWorks', CollectionType::class, [
'data' => $quoteItem->getQuoteItemAdditionalWorks(),
'label' => false,
'mapped' => false,
'entry_type' => QuoteItemAdditionalWorkType::class,
'entry_options' => ['label' => false],
'by_reference' => false,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
]);
}
表单收集在表单上可以正常工作,但是在提交并尝试从控制器中的学说实体中删除收集项时,这些项不会被删除。删除项目的控制器代码如下
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$quoteItem->setDrawingNumber($form->get('drawingNumber')->getData());
$quoteItem->setDrawingRevision($form->get('drawingRevision')->getData());
$updatedAdditionalWorkItems = $form->get('quoteItemAdditionalWorks')->getData()->unwrap();
foreach ($quoteItem->getQuoteItemAdditionalWorks() as $existingAdditionalWorkItem) {
if (false === $updatedAdditionalWorkItems->contains($existingAdditionalWorkItem)) {
$em->remove($existingAdditionalWorkItem);
}
}
$em->persist($quoteItem);
$em->persist($workOrder);
$em->flush();
}
我不知道这是我在symfony还是教义中做错了什么。从未映射的表单集合字段中的集合中删除项目时,我该怎么做?
答案 0 :(得分:1)
请尝试这个
foreach ($quoteItem->getQuoteItemAdditionalWorks() as $existingAdditionalWorkItem)
{
if (false === $updatedAdditionalWorkItems->contains($existingAdditionalWorkItem))
{
$quoteItem->getQuoteItemAdditionalWorks()->removeElement($existingAdditionalWorkItem);
$em->remove($existingAdditionalWorkItem);
}
}