I have profiles and studies. One person can finish many studies. The form renders correctly. There is a button \"Add new study\" and with jQuery I add another subform based
Your solution did not work for me. In fact I had already set up the relationship and defined the adder, remover, getter and after I saw your solution i added the setter.
However my setter was not called when the form was submitted.
The solution for me was another one.
In the adder method I added a call to set the owner.
public function addStudie($studie)
{
$studie->setProfile($this);
$this->studies->add($studie);
}
And to have this adder called when the form is submitted you need to add to the form collection field the by_reference
property set to false
.
$builder->add('study', 'collection', array(
'type' => new StudyType(),
'allow_add' => true,
`by_reference` => false,
'allow_delete' => true
)
)
Here is the documentation:
Similarly, if you're using the CollectionType field where your underlying collection data is an object (like with Doctrine's ArrayCollection), then by_reference must be set to false if you need the adder and remover (e.g. addAuthor() and removeAuthor()) to be called.
http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference
You have to set profile to instance. In controller. You havent pasted controller code.. You should iterate over $profile->getStudy collection and set for each item ->setProfile=$profile.
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html#use-case-1-dynamic-attributes
What is happening there doesnt apply to forms..He actually has a this reference..Hm maybe adding this is a kind of auto fix to avoid iteration, not sure whether it works, i'll try
If i understand you correctly your relation is bidirectional, so you have to specify an owning side and an inverse side. As Doctrine 2 documentation:
So i messed up with your association in my first answer. In your case Profile
has to be the inverse side while study should be the owning side. But you are working on Profile
, so you need the cascade
annotation on profile to persist new entities:
class Profile
{
/**
* Bidirectional (INVERSE SIDE)
*
* @ORM\OneToMany(targetEntity="Study", mappedBy="profile",
* cascade={"persist", "remove"})
*/
private $studies;
}
class Study
{
/**
* Bidirectional (OWNING SIDE - FK)
*
* @ORM\ManyToOne(targetEntity="Profile", inversedBy="studies")
* @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
*/
private $profile;
}
Note that your example is exactly the same as that on Doctrine2 documentation.