Search code examples
symfonysymfony-forms

Symfony HiddenType for a DateTime object


I have a simple form

   ->add('createDateTime', HiddenType::class)

Causing an error:

Object of class DateTime could not be converted to string

How do I work around this issue? I don't want to change the entity to return a string formatted date...

Any ideas?


Solution

  • As form inputs require a text representation of the data, you'll need to convert the value to a string with the help of a DataTransformer. Fortunately, Symfony comes with a transformer for DateTime objects, you just need to add it to your form field:

    $builder
        ->add('field') //...
        ->add('createDateTime', HiddenType::class);
    
    $builder
        ->get('createDateTime')
        ->addModelTransformer(new DateTimeToStringTransformer());
    

    You can specify different timezones for conversion or format if you need to.