Sunday, 11 August 2013

Symfony2, manipulate form between submission and validation

Symfony2, manipulate form between submission and validation

Using Symfony2 for a little while now, I ran into a problem on my current
development : I need to edit the data sent by a form before it gets
validated. Here's the situation :
My form contains two important fields : "name" and "domain".
"domain" refers to an entity, which has a property "domain_name".
Now, imagine "name" is set to "mywebsite" (using the form), and that the
domain is set to "mydomain.com" (entity field selecting domains in a
database) :
form[name] : "mywebsite"
form[domain] : Object (domain_name => "mydomain.com")
What I want to achieve is to change the value of the "name" field
according to the selected domain. I want to append "domain_name" to
"name", in order to get :
form[name] : "mywebsite.mydomain.com"
form[domain] : Object (domain_name => "mydomain.com")
I found 2 solutions but they don't seem to fit the situation :
Data transformers. Seems to work on one field only, however, in order to
edit "name", I need to access the "domain" entity from the form, which is
not available in the Data Transformer class. What I may be looking for is
a way to apply a data transformer on the whole form (but I didn't find a
way to do this...)
Form events. This will edit the "name" field before submission, but I want
my modifications to happen after (this way, the user cannot alter them).
Is there a solution I've missed ?

No comments:

Post a Comment