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

前端 未结 5 568
滥情空心
滥情空心 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:53

    So a year has passed, and this question has become quite popular. Symfony has changed since, my skills and knowledge have also improved, and so has my current approach to this problem.

    I've created a set of form extensions for symfony2 (see FormExtensionsBundle project on github) and they include a form type for handleing One/Many ToMany relationships.

    While writing these, adding custom code to your controller to handle collections was unacceptable - the form extensions were supposed to be easy to use, work out-of-the-box and make life easier on us developers, not harder. Also.. remember.. DRY!

    So I had to move the add/remove associations code somewhere else - and the right place to do it was naturally an EventListener :)

    Have a look at the EventListener/CollectionUploadListener.php file to see how we handle this now.

    PS. Copying the code here is unnecessary, the most important thing is that stuff like that should actually be handled in the EventListener.

提交回复
热议问题