symfony/symfony — pull request #5301 by hansallis (2012-08-20 09:28:15+00:00)
Title: [WIP] [Form] Added a deletion_handler option to the collection type to handle deletion of entries

When allow_delete is enabled on a CollectionType form element, it's sometimes necessary to delete missing entries from the database through the ORM. Currently, adder/remover methods are called on the domain object that contains the collection, but the domain object isn't able to remove entries from the underlying database.

In many cases, the orphanRemoval option offered by Doctrine is a good way to handle this. I ran into trouble with (let's say) a StockMutation entity that was either owned by an Order or a StockCorrection entity (OneToMany on the Order and StockCorrection classes). When binding a form for an Order, all StockMutations that were part of a StockCorrection would be deleted by Doctrine as they're considered to be orphans.

Using this deletion_handler option, I can pass a closure to the form collection. This closure gets called whenever an entry is found to be deleted upon form submission, at which point it can i.e. call the remove method on Doctrine's EntityManager.

After creating this patch, I found that it's also possible to subclass the StockMutation class using single-table-inheritance. This allows me to use orphanRemoval without problems. However, since I created this patch already, I'd like to hear people's opinions and find out if there might be situations where this actually fulfills a requirement for anyone.

If so, I'll add the necessary tests as well to make this feature more complete.

Bug fix: no
Feature addition: yes
Backwards compatibility break: no
Symfony2 tests pass: yes
Fixes the following tickets: n/a
Todo: Write tests
License of the code: MIT
Documentation PR: n/a