Reputation: 870
Problem: My many-to-many relationship is not being saved
The form is rendered correctly with checkboxes, and if I manually add a relation between a datatypegroup and a datatype the checkbox is also checked.
But if I check another datatype and save the form, the new relation is not established. I have tried with and without by_reference in the form, but no luck. The addDatatype method on the datatypegroup entity is not called either. Do I really have to loop the form data and find the entities myself?
FormBuilder:
$builder
->add('name', 'text')
->add('datatypes', 'entity', array(
'by_reference' => true,
'multiple' => true,
'expanded' => true,
'class' => 'T\DBundle\Entity\Datatype',
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
$qb = $er->createQueryBuilder('d');
return $qb->orderBy('d.name', 'ASC');
}
));
DoctrineMapping:
T\DBundle\Entity\DatatypeGroup:
type: entity
table: DatatypeGroup
manyToMany:
datatypes:
targetEntity: T\DBundle\Entity\Datatype
mappedBy: datatypeGroups
T\DBundle\Entity\Datatype:
type: entity
table: Datatype
manyToMany:
datatypeGroups:
targetEntity: T\DBundle\Entity\DatatypeGroup
inversedBy: datatypes
joinTable:
name: Datatype_DatatypeGroup
joinColumns:
datatype_id:
referencedColumnName: id
inverseJoinColumns:
datatypeGroup_id:
referencedColumnName: id
Controller:
/**
* @Route("/edit/{id}", name="edit")
* @Secure("ROLE_USER")
* @Template("TDBundle:DatatypeGroup:form.html.twig")
*/
public function editAction(Request $request, DatatypeGroup $datatypegroup) {
$editForm = $this->createForm(new DatatypeGroupType(), $datatypegroup);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
/** @var EntityManager $em */
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirect($this->generateUrl("edit",array("id" => $datatypegroup->getId())));
}
return array(
'datatypegroup' => $datatypegroup,
'form' => $editForm->createView(),
);
}
Upvotes: 1
Views: 7355
Reputation: 870
I do not know how to mark this as a duplicate, but I finally found a question answering my question: Symfony2 Doctrine2 Many To Many Form not Saving Entities
The doctrine mapping had to be reversed so that the datatypegroup was the owning type of the relationship.
Upvotes: 5