In a nutshell:
When I am using 'sonata_type_collection' in OneToMany relationship I have to specify the other side of the relation, which in the "create action" still does not exist and in "update action" could be set, but it is also possible to specify entirely different parent.
More detailed explanation:
I am using Sonata Admin Bundle for the CRUD operations and lets say that I have only Post(id, title, content) and Tag(id, post_id, title) entities. I would like to be able to add and remove tag entities while I am editing the Post entity, so I use 'sonata_type_collection' field.
This is the configureFormFields method from the PostAdmin class:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
->add('content')
->add('tags', 'sonata_type_collection', array(), array(
'edit' => 'inline',
'inline' => 'table'
))
))
;
}
The problem is that in the create form, when I add new tag I have to specify both post and title, but the Post still does not exist, so I am not able to add tags. While I am editing the post I could add new tags, but for every one of them I have to explicitly set a post, and I am able for example to add a tag for entirely different post.
Could you tell me how to solve this problem?
You might want to set the by_reference option to false.
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
->add('content')
->add('tags', \Sonata\CoreBundle\Form\Type\CollectionType::class,
array('by_reference' => false),
array('edit' => 'inline',
'inline' => 'table'
)
);
}
[edit] So it looks like the problem was coming from the Post entity which had to call tags' setPost() method from the addTag() method.
public function addTag($tag)
{
$tag->setPost($this);
$this->tags->add($tag);
return $this;
}