I am working with Symfony 3.x and Doctrine. I have a collection entity, quoteItemAdditionalWork, that is in association with QuoteItem entity. I have another entity called WorkOrder. The WorkOrder entity is a designated data_class for the form, WorkOrderType. On the WorkOrderType form I need to include form elements from the QuoteItem entity as unmapped form fields (one data_class per form type -symfony rule ). The form collection quoteItemAdditionalWork is one of the form fields included in the WorkOrderType form and is unmapped on the form as quoteItemAdditionalWork has no entity association with 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,
]);
}
The form collection works fine on the form, but on submission and attempting to remove the collection items from the doctrine entity in the controller the items are not removing. The controller code for removing items looks like
$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();
}
I don't know if this is something I am doing wrong in symfony or in Doctrine. What am I doing wrong in removing items from the collection in an unmapped form collection field?
Please try this
foreach ($quoteItem->getQuoteItemAdditionalWorks() as $existingAdditionalWorkItem)
{
if (false === $updatedAdditionalWorkItems->contains($existingAdditionalWorkItem))
{
$quoteItem->getQuoteItemAdditionalWorks()->removeElement($existingAdditionalWorkItem);
$em->remove($existingAdditionalWorkItem);
}
}