Symfony2: how to change form value before validation

I have the following situation:

  • form field type date
  • validation pattern e.g. dd.mm.YYYY
  • auxiliary object, which turns 12 into 12.07.2012 or 2.5 into 02.05.2012 , etc.

My question is: where can I call a method that converts the input value?

When I call it from the set method of the object, the value actually changes. But when you reload the form (for example, incomplete submission), the old value (for example, 2.5 ) is displayed, and not the converted value ( 2.5.2012 ). Now, how do you tell the form that the value has changed inside the object?

Maybe there is another way to do this between:

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

Php

This is from an object:

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

This is of 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, )); 
+6
source share
1 answer

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

From the sound of your case, I think DataTransformer makes sense. You present the data in the object in one way, but you need to present it in the form differently and change this transformation when submitting the form. This is the goal of DataTransformer.

+11
source

Source: https://habr.com/ru/post/919782/


All Articles