Symfony2 form and Doctrine2 - update foreign key in assigned entities fails

前端 未结 3 2130
广开言路
广开言路 2021-01-03 08:50

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

3条回答
  •  迷失自我
    2021-01-03 09:17

    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

提交回复
热议问题