Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default value on form value transformer in Symfony2

Tags:

php

symfony

I have the following form type set up in Symfony2 and I'm trying to add a default value to dateField but can't seem to get it to work.

In "Tried 1" below I get a "The form's view data is expected to be an instance of class DateTime, but is a(n) string" error... which puzzles me a little because if I give a string it tells me it needs to be a DateTime object, and in "Tried 2" it runs without errors but no default values are changed. Currently the form defaults to '-0001-11-30 00:00:00'. Is there any way to set these defaults like this?

$builder
        ->add(
            $builder->create('dateField', 'hidden' )->addViewTransformer( new DateTimeToStringTransformer() )
        )
        ->add('field2', 'hidden')
        ->add('field3', 'hidden')
        ->add('submit', 'submit')
        ->getForm();

Tried 1:

->add($builder->create('boutDate', 'hidden', array('data' => new \DateTime()))->addViewTransformer( new DateTimeToStringTransformer() ))

Tried 2:

->add(
    $builder->create('boutDate', 'hidden' )->addViewTransformer( new   DateTimeToStringTransformer() ),
        'hidden',
        array('data' => '2014-01-02')
)
like image 267
john Avatar asked Dec 07 '14 10:12

john


1 Answers

You don't have to use transformer. Just set string default value

$builder
        ->add($builder->create('boutDate', 'hidden', array('data' => '2014-01-02')))
        ->add('field2', 'hidden')
        ->add('field3', 'hidden')
        ->add('submit', 'submit')
        ->getForm();
like image 130
mleko Avatar answered Oct 23 '22 04:10

mleko