Embedding a collection of forms Symfony2 forms with adding and deleting allowed

doctrine-orm, php, symfony

Solution

If you want to index the collection (by the entity id) for all querys, you can simply use the `indexBy` annotation in your entity class.

/**
 * @ORM\OneToMany(targetEntity="EntityClass", mappedBy="EntityVariable", indexBy="id")
 */
private $collection;

Problem

In Symfony2, if I embed a collection of forms pointing at a many to one relationship in Doctrine and allow adding and deletion, if I delete a record from the beginning, add one at the end, and edit some in the middle how does the system know which records to update with which data? There is nothing in the tutorial that passes the primary key of the embedded data around. Under certain circumstances, my records are getting needlessly deleted and added again rather than edited in place (even if there are no changes to the particular record). This breaks the fields on the records that are not included on the form, setting them to their default values from the DB model. Is there a way to pass the primary key in the form and have it used to perform updates when the data comes back?

Original source