symfony: One to many relationship doesn't behave as expected when using collections in forms

When using entity’s in Doctrine with one-many relationships using a form collection, Symfony does not assign the parent entity to the child entity. Using ‘by_reference’ => false with cascade-persist fails and the child entity’s foreign key is null in the database.

The following appears to remedy the issue within the set method which accepts an ArrayCollection within the entity.

        foreach($links as &$link){
            $link->setHub($this);
        }

Surely Symfony should do this within bindRequest in the form itself?

About this issue

  • Original URL
  • State: closed
  • Created 12 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

The form component does not know anything about Doctrine, which has a requirement to update the owning side of the relation. Btw, if you don’t set the hub when adding a link, it will always fail to add it. This is why it is recommended to do ->setHub() in the setter of the inversed side. This is a Doctrine requirement which is documented in the doctrine doc about relations. altering the Symfony form component for such cases is wrong as it would couple it to Doctrine (to be able to detect inversed-side of relations) Btw, this requirement is one of the reason why the code generated by the EntityGenerator should be considered as a starting point for the entities, not as a ready-to-be-used-blindly code.