-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
Option to index CollectionType by ID, not by incrementing number #34453
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Can you explain how the solution for this would be different from a solution for #7828? |
I'm not sure how the solution of #7828 translates to HTML. So I expanded more on this aspect. I can't say if it's really the same or just looks similar ;-) Anyway, the problem I'm addressing here (risk of ruining your table) should be explained at https://symfony.com/doc/current/form/form_collections.html Should I open a ticket at https://github.com/symfony/symfony-docs ? |
CollectionType gets indexed by whatever your array is indexed by (as that's what allow writing back). The solution in your case is to index your list of users in the data you set in the form. |
@stof awesome - thanks! This resolves the issue I'm talking about here, so I'm closing it. However, I opened symfony/symfony-docs#12656 as I think there should be a best practice in the docs. BTW: Here's an easy way how to get the ID-indexed array directly from the Repository: https://stackoverflow.com/a/58976877/1668200 |
The Problem
The main use case of CollectionType is an entity with an associated child entity (with features like
allow_add
andallow_delete
). I'm talking about a different situation:If you have just one entity, you can use a CollectionType to edit (say) 100 existing rows at once, and persist them with just one single form submission.
So far, so good.
But what if the underlying database table changes while you have the form on your screen? This will end up in the submitted field values being persisted to the wrong entities, thereby effectively destroying your table!
Why is that?
$userRepository->findSomeUsers()
is executed again. And ifusers[0]
is not the same row as before, its values are being overwritten.Suggested Solution
Add an option like
'index_by' => 'id'
to CollectionType which results in using the row's ID for the index in HTML:If I understand it right, this solution has been suggested before at #7828 but for solving a different problem. I'm opening this new ticket here to illustrate another use case that would also benefit from that feature.
The text was updated successfully, but these errors were encountered: