2

I need to know whats the usual way to handle datetime via forms.

I have a property in my entity like

/**
 * @var \DateTime
 *
 * @ORM\Column(name="founded", type="datetime", nullable=true)
 */
private $founded;

Then i render the form via FormTypes

->add('founded', 'date', array('widget' => 'single_text', 'format' => 'dd.MM.yyyy'))

The user then inputs a string like 01.01.1892 And sends it to the server via ajax:

form_team[basicdata][founded]:01.01.1914

In the controller i process the data and validate it:

$form = $this->createForm(new TeamsType(), $team);
$form->submit($this->getRequest()->request->get($form->getName()));

if ($form->isValid()) {
...

The thing is, that validation allways fails with: This value is not valid. I guess a datetime object is expected, but the client just delivers a string.

How is that workflow supposed to be working? Please help me with that :)

3
  • 2
    I think you should use datatransformer to transform the client data to datetime. see symfony.com/doc/current/cookbook/form/data_transformers.html Commented May 6, 2014 at 13:53
  • i guess this is a day to day issue. how is it normaly done? there should be already solutions for this i think... ? Commented May 6, 2014 at 14:36
  • I need to know what the validation needs to get her. i cant the hell figure it out what is the client supposed to send. its impossible to send 01.01.1893 for example, i allways get "This value is not valid." i have no clue where the error is throwen and what it expects to get to not throw that error.... Commented May 7, 2014 at 12:08

1 Answer 1

1

@Benjamin Lazarecki is right.

You need to transform the string data (comming from within your form) to DateTime object. However, that transformer has been already implemented here:

http://api.symfony.com/master/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.html

So, you can just and plug 'n' play it ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Is this the usual way? I dont get it why i have to transform the object manually when i use the form component, isnt it supposed to handeled automatically buy the framework? i guess its a usual usecase to render a datetime property of an entity in a forminput and process it back to server. i can configure the 'input' => 'datetime' parameter in the formtype, so i guess it should be handeled automatically
You have to use transformer because you have change the widget.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.