0

How to set default date for symfony html5 form widet from the controller ?

$date = date(d-m-Y); //todays date

...
    ->add('starts', 'date', [
        'widget' => 'single_text',
        'format' => 'dd-MM-yyyy',
        'placeholder'=>$data,
    ])
...

'placeholder'=>$data does nothing. After page is loaded my form input contains dd.mm.yyyy

3 Answers 3

2

Try this

      ->add('starts', 'date', [
            'widget' => 'single_text',
            'format' => 'dd-MM-yyyy',
            'data' => new \DateTime()
        ])
Sign up to request clarification or add additional context in comments.

2 Comments

@GlupiJas I tested it on Symfony 3 - chrome exacly like below and it worked ->add('starts', DateType::class, [ 'widget' => 'single_text', 'format' => 'dd-MM-yyyy', 'data' => new \DateTime(), 'mapped' => false ])
Perhaps you are right but something prevent it from working in my project. Does it work in Syfony 2.7 ?
0

If your form is linked to a model object, set your date on that object.

Comments

0

OK I had to create an associative array that holds the name of the field and its default value. I had to pass that array to the createFormBuilder() method as a first parameter.

$defaultData = [
    'starts' = new \DateTime()
];

$form = $this->createFormBuilder($defaultData, ['attr'=>['novalidate'=>'novalidate'])
->add(...)
...

I could also set first parameter to null and add default data using:

$form = $this->createFormBuilder(null, ['attr'=>['novalidate'=>'novalidate'])
->add(...)
->getForm();
$form->setData($defaultData);

this also worked for me.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.