2

How would I go about setting the default value of the datetime field of a form to the current time in Symfony2?

I'm using the FormBuilderInterface and the following isn't working:

$builder->add(
    'completed_datetime', 'datetime', array('data' => new \DateTime('now'))
);

The form continues to show what I presume to be the default value for the datetime field 2008-01-01 00:00.

13
  • 1
    What does it do instead? Are you getting some error? Not working is not saying much, you know? Commented Jan 7, 2013 at 10:53
  • 1
    Normally not, please run code like this verbatim on your system and see if you're not getting now. eval.in/6082 Commented Jan 7, 2013 at 10:58
  • 1
    Are you reading/importing the 2008 date from other objects that overwrite it later? E.g. probably with database access or entities that have a default value? Commented Jan 7, 2013 at 11:02
  • 1
    Sure, otherwise I'd say it overwrites it. See as well Set default value on Datetime field in symfony2 form Commented Jan 7, 2013 at 11:05
  • 1
    lol, yeah that happens. I have a no-chache setting in firefox with the webdeveloper toolbar so it does not happen clearly ;) for local development, the speed is still okay even w/o caching then. Commented Jan 7, 2013 at 11:08

1 Answer 1

4

In the end it turned out I was viewing a cached version of my page. Ctrl+F5 cleared the cache and showed the desired result.

I was able to achieve the functionality I wanted in both the ways posted here, i.e.:

In the Type class:

$builder->add(
    'completed_datetime', 'datetime', array('data' => new \DateTime('now'))
);

And in my controller:

$task->setCompletedDateTime(new \DateTime('now'));

I believe it's also possible to set it in my Task Entity class' constructor.

Sign up to request clarification or add additional context in comments.

3 Comments

Doing that in the class constructor might have side effects or lead to wrong results. Remember that the class constructor is also executed when Doctrine loads your entities from the database.
How do you solve the issue @likeitlikeit because I'm stuck with current time when editing?
using 'data' option will set the field to datetime now even on edits. This is not always desired.

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.