Going crazy, with Symfony 3.
The question is: What would be the proper way to set a value into a Symfony form, with simply setting the viewData instead of the modelData, and the form would take care of the transformation?
...with a small catch: without the usual form/request creation and handling. :)
Something like (presuming we're setting a field which is a DateTime in the DB):
$form = $this->createForm(ProperForm::class, $existingData);
$form->setPlainScreenFormattedData('myDateField', '11/29/2016');
which would convert the given date into a proper \Datetime object and nicely set it in the form?
Example and explanation:
I'm using a package for inline editing of HTML table data (Tabledit) and kind of have to stay with that package (due to time/space issues). It sends following data (by ajax) to the server:
- name of the form field
- ID of the data in DB
- new value to be persisted to DB
That's all nice and plays well with the saving controller - as long as it works with plain textual data. When you try to change an EntityType, or some Datetime field with it - it breaks. And it breaks, because I try to set a plain, for-screen formatted value into either the form or the underlying object of the form.
To prevent the breaking and still have a one-for-all solution, I tried various forms of creating the given form and using, for example:
- $form->get($field)->setData($value)
- $form->setData([$field => $value)])
- $form->getData()->AProperFieldSetterName($value)
and more (like here), but none of those work, because basically, all of those are expecting for the $value to be a modelData (like it's said here).
My reasoning
I would not like to create new data transformers for this - because they are already in, Symfony knows about this form and its underlying object structure. Also, I would not like to need to change existing solution, and to stop sending individual fields to the controller, for updating.
I could solve this with creating some manual calls to the DB to first fetch the proper hydrated objects for each field, based on given ID (like $em->getRepository('somerepo')->find($value)
(for entities), or manually creating the Datetimes, and then feeding that to the form) but this all seems non-good and doubling the existing functionality.
Is there a simple way to do this data transformation? It feels like there should be one. Or did I went too far into non-Symfony ways and got lost?