0
votes

I'm working with Symfony2 to set up a form, where a Shelf-Entity can be edited.
A shelf contains a collection of Readable-Entities (e.g. Book, Magazine, etc. - all inherit from Readable).
The user has the possibility to add more Readable-Entities (the form is extended via JavaScript) and from a dropdown he can select the type of Readable he wants to add. Depending on the selected dropdown-value, different form fields are rendered. So far so good.

Now, when the form is submitted to the server, depending on the Readable-Type the user selected in the form, a different entity-type should be instantiated. If I don't do anything, Symfony just instantiates the base class Readable (and not Book, Magazine, etc.).

How can I tell Symfony to instantiate the correct type of Readable depending on the selected value from the dropdown?

I tried with FormEvent-Listeners, but:

  • in PRE_SUBMIT I only get an array containing the "raw" form data with $event->getData(), i.e. no entities have been instatiated so far. However, at this stage, I still have access to value of the dropdown.
  • in SUBMIT the form data was already assigned to the appropriate entities. Also the new Readable was already instatiated with the base Readable-Class. But now, I cannot access anymore the value from the dropdown.

What is the correct way to do this?

EDIT
Added a minimal Code-Example for the Shelf FormType:
https://gist.github.com/anonymous/401495b701982adafb96
Code for infinite_form_polycollection:
https://gist.github.com/anonymous/b5f0ed10ca9c52177f01

2
Can you provide a bunch of your code please Stefan? - Yoann Chambonnet
I'm not sure, which code you would like - I added a bit of the Shelf FormType Code above. If you would like something else, please say so. - Stefan
sorry for insisting, but did you have a chance to look at the code? - Stefan
Hey Stefan. I could give a short look at your code but can't really find a solution for your problem. Maybe the matter is a design one? - Yoann Chambonnet
Hey YoannCh, thanks! Well, I'm not a design-expert at all :-) So how would you implement/redesign this if there are several subtypes of a common basetype? I thought generics/inheritance was exactly for this? (note: the readable/book-scenario is just a simplified example but maps well to the real problem) - Stefan

2 Answers

0
votes

Have you tried looking at this part of the doc? As "embedding a form" seems to fit your needs.

0
votes

It seems that there was something wrong with the PHP-Files of the PolyCollection in the vendor-directory, because after removing everything related to the Infinite Form Bundle from the vendor-dir and reinstalling it with composer, everything is working now. But thanks for your efforts YoannCh