The default date on the form (symfony2)

I create a form using Symfony2:

$builder
                ->add('days', 'date', array(
                    'widget' => 'choice',
                                    'format' => 'dd-MM-yyyy',
                                    'pattern' => '{{ day }}-{{ month }}-{{ year }}',
                                    'years' => range(Date('Y'), 2010),
                                    'label' => 'Inactive participants since',
                                    'input' => 'string',
                    ));

But I want to show the default date, for example, today, so when I print the form, I see

02 - 05 - 2012

Any idea?

+3
source share
3 answers

Does this date work?

 $builder
                    ->add('days', 'date', array(
                        'widget' => 'choice',
                                        'format' => 'dd-MM-yyyy',
                                        'pattern' => '{{ day }}-{{ month }}-{{ year }}',
                                        'years' => range(Date('Y'), 2010),
                                        'label' => 'Inactive participants since',
                                        'input' => 'string',
                                        'data'  => '01-01-2001'
                        ));
+4
source

You must set a default date before the form.

When you create your object ( $entity = new Entity();), just add your default value, for example:

$entity->setDays(my_value);

And if you want to add today's date, you can use the DateTime function as follows:

$entity->setDays(new \DateTime());

I hope I'm clear enough.

+1
source

For version 2.1, the default form will be installed by default:

 $builder
                    ->add('days', 'date', array(
                        'widget' => 'choice',
                                        'format' => 'dd-MM-yyyy',
                                        'pattern' => '{{ day }}-{{ month }}-{{ year }}',
                                        'years' => range(Date('Y'), 2010),
                                        'label' => 'Inactive participants since',
                                        'input' => 'string',
                                        'data'  => date_create()
                        ));
0
source

All Articles