John WH Smith
John WH Smith

Reputation: 2773

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 :

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) :

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 :

I found 2 solutions but they don't seem to fit the situation :

Is there a solution I've missed ?

Upvotes: 2

Views: 311

Answers (1)

Alexey B.
Alexey B.

Reputation: 12033

You can modify submitted data in form.PRE_BIND event. This event occurs then you call $form->bind($request) in controller. How to add event subscriber to form. Keep in mind that you have to deal with bare data that is not converted to entities etc.

Applying Data Transformer to entire form very easy - just dont specify field. For example

$builder
    ->add('name', 'text')
    ->add('domain', 'entity')
    ->addModelTransformer($transformer);

vs

// add a normal text field, but add your transformer to it
$builder->add(
    $builder->create('name', 'text')
        ->addModelTransformer($transformer)
);

Upvotes: 1

Related Questions