Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: How to modify a form value before validation

I have the following situation:

  • a form field type date
  • a validation pattern like dd.mm.YYYY
  • a helper object that turns 12 into 12.07.2012 or 2.5 into 02.05.2012 etc.

My question is: Where do I call the method that transforms the input value?

When I call it from the set-method of the entity, the value actually gets changed. But when loading the form again (e.g. incomplete submit) the old value (like 2.5) and not the transformed value (2.5.2012) is shown. Now, how do I tell the form, that the value has changed within the entity?

Maybe there's also another way of doing it in-between:

$form->bindRequest($request);
// do some fancy stuff here
if ($form->isValid()) {}

PHP

This is from the Entity:

/**
 * @ORM\Column(type="datetime", nullable=true)
 * @Assert\DateTime()
 */
protected $date_start;

This is from the Type:

$builder->add('date_start', 'datetime', array(
    'label' => 'Start Datum/Uhrzeit',
    'date_widget' => 'single_text',
    'time_widget' => 'single_text',
    'date_format' => 'dd.MM.yyyy',
    'with_seconds' => false,
    'required' => false,
));
like image 461
insertusernamehere Avatar asked Jul 05 '12 16:07

insertusernamehere


1 Answers

There are two ways to modify forms and the data bound to them. You can use form events, there is an example of their use here or you can use a DataTransformer which is explained here

From the sound of your case I think a DataTransformer makes the most sense. You are representing the data in the object in one way but you need to present it in the form in a different way, and reverse that transform when the form is submitted. This is purpose of the DataTransformer.

like image 79
MDrollette Avatar answered Oct 11 '22 22:10

MDrollette