简体   繁体   中英

Symfony2.0 form date with today

I create a form in symfony2.0 and read some articles here. But all doesn't work.

I want to create a form field with the type date and the date should be today. What is wrong?

            ->add('date', 'date', array(
                'input'  => 'datetime',
                'widget' => 'choice',
                'format' => 'dd-MM-yyyy',
                'data'  => new \DateTime() //new \DateTime('today') didn't work
            ))

I don't have an entity.

Error message:

Expected argument of type "DateTime", "array" given

How do I pass it right in Symfony2.0?

Update: Answer

A little bit too much code, but this is the answer.

Before the form builder:

$dt = new \DateTime();

The form builder:

....
'input'  => 'array',
'widget' => 'choice',
'format' => 'dd MM yyyy',
'data'  =>  array('year' => $dt->format('Y'), 'month' => $dt->format('m'), 'day' => $dt->format('d')), 
....

In your entity, set the datetime to your field like that :

/**
     * Constructor
     */
    public function __construct()
    {
        $this->date = new \DateTime();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM