I’ve a Candidate entity which have an $xmlContent attribute, This attribute is used to get some references to other Entities (Country, Citizenship, …), the $xmlContent value contain the Ids of these entities as follow,
<data>
<countryId>2</countryId>
<citizenship>4</citizenship>
<!-- ... -->
</data>
Note: I know, The model was badly designed! I can’t modify it, This was one of the project weird constraints when I started working on it.
So, I created getters and setters for each Id of the $xmlContent value.
The problem,
I created a Form to edit a Candidate object (including the $xmlContent Ids), I then Added getters and setters to get these values (getCountry(), getCitizenship(), …)
The problem is that I want to let the user choose the value of Country (for example) from a list of all available countries, I also have to put the right country as a default one.
I then decided to use an Entity Field,
->add('country', 'entity', array(
'class' => 'MyBundle:Country',
'query_builder' => function(CountryRepository $er) {
return $er->createQueryBuilder('c')
->orderBy('c.rank', 'ASC');
},
'property' => 'Name'
))
But, here I had another problem, the getter I’m using to get a candidate Country returns an “Id” but the Entity Field expect an Object.
My Question,
What is the best way to handle this?
My Constraint,
I want to keep my code as clean as possible 🙂
Maybe you should look into DataTransformers and EventSubscribers.
You could use a DataTransformer to parse you
xmlContentinto discrete properties and populate their fields, e.g.countryandcitizenship.Using an EventSubscriber you can a) on
PRE_BINDreverseTransform the form data intoxmlContent* and b) transform your form elements, e.g. fetch countries and create/alter a choice-elementcountryfrom the data.* DataTransformers won’t work here, as you do not just want to reverseTransform, i.e. string into entity, but rather want to merge and transform data from multiple fields (country, citizenship, etc.) into a single field (xmlContent).