ArrayCollection (Collection of forms) index collision in Symfony 2 ArrayCollection (Collection of forms) index collision in Symfony 2 javascript javascript

ArrayCollection (Collection of forms) index collision in Symfony 2


Yes, this is problem of Symfony form collection and it has no easy solution imho. But I have to ask why don't you do exactly the same thing what page refresh does? You can refresh only html snippet with collection. HTML code for snippet can come from server-side. Back to your question - yes, reindexing is good solution until you do not want to try write custom collection type on your own.

symfony/symfony/issues/7828

There is similar problem with validating in collection - symfony/symfony/issues/7468.

Well I think default collection type and the tutorial in Symfony docs has the some drawbacks. Hope that's help.


I have come round this issue on the client side by modifying the Javascript/Jquery code given in the Symfony Documentation.

Instead of numbering the new elements by counting the sub-elements, I am looking at the last element's id and extracting its index with a regular expression.

When adding an element, I am incrementing the last index by 1. That way, I never use the same index.

Here is my code :

// Initializing default index at 0var index = 0;// Looking for collection fields in the formvar $findinput = $container.find(':input');// If fields found then looking for last existing indexif ( $findinput.length > 0 ) {    // Reading id of last field    var myString = $findinput.last().attr('id')    // Setting regular expression to extract number from id containing letters, hyphens and underscores    var myRegex = /^[-_A-Za-z]+([0-9]+)[-_A-Za-z]*$/    // Executing regular expression on last collection field id    var test = myRegex.exec(myString);    // Extracting last index and incrementing by 1    if (test.length > 0) index = parseInt(test[1]) + 1;}


I ran into this problem a couple of times during the past two years. Usually, following the Symfony tutorial How to Embed a Collection of Forms does the job just fine. You need to do a little bit javascript coding to add the "edit/update" functionality, but other than that - you should be just fine using this approach.

If, on the other hand, you have a really complex form which uses AJAX to validate/save/calculation/business logic/etc, I've found it's usually a better to store the final data into an array in the session. After submitting the form, inside the if($form->isValid()){...} block, you would have

$collection = new ArrayCollection($mySessionPlainArray);$user->setAddress($collection);

I would like to warn you to be careful with the serialization of your data - you might get some awkward exceptions or misbehavior if you're using entities (see my question).

I'm sorry I can't provide more code, but the solution to this problem sometimes is quite complex.