Symfony2 collection of Entities - how to add/remove association with existing entities?

前端 未结 5 570
滥情空心
滥情空心 2020-12-04 06:56

1. Quick overview

1.1 Goal

What I\'m trying to achieve is a create/edit user tool. Editable fields are:

  • username (type: text)
  • plai
5条回答
  •  隐瞒了意图╮
    2020-12-04 07:49

    This is what I have done before - I don't know if it's the 'right' way to do it, but it works.

    When you get the results from the submitted form (i.e., just before or right after if($form->isValid())), simply ask the list of the roles, then remove them all from the entity (saving the list as a variable). With this list, simply loop through them all, ask the repository for the role entity that matches the ID's, and add these to your user entity before you persist and flush.

    I just searched through the Symfony2 documentation because I remembered something about prototype for form collections, and this turned up: http://symfony.com/doc/current/cookbook/form/form_collections.html - It has examples of how to deal correctly with javascript add and remove of collection types in forms. Perhaps try this approach first, and then try what I mentioned above afterwards if you cannot get it to work :)

提交回复
热议问题