51

I have a form containing several fields. One of them is a Datetime field. How to define a default value for that field?

I've tried setting a value on the related entity, in controller, in constructor and __construct :

$myEntity = new MyEntity();
$myEntity->setMyDate(new \DateTime());
$form = $this->createForm(new AddMyEntity(), $myEntity);

Not working.

Tried to define the $data variable in the buildForm :

$builder->add('myDate', 'date', array(
    'format' => \IntlDateFormatter::SHORT,
    'input' => 'datetime',
    'widget' => 'single_text',
    'data' => new \DateTime("now"));

Not working either. Any ideas, Symfony2 community?

EDIT : Adding entity on demand of faost.

/**
 * @ORM\Column(name="myDate", type="datetime")
 * @Assert\NotBlank()
 */
private $myDate;
DerpyNerd
  • 4,743
  • 7
  • 41
  • 92
i.am.michiel
  • 10,281
  • 7
  • 50
  • 86
  • Please show definition of the property "myDate" in class "MyEntity" and method "buildForm" of form type class "AddMyEntity". – alexfv Jan 03 '12 at 15:04
  • The second part of my question is a extract of the buildForm method. And I'll add the entity part. – i.am.michiel Jan 03 '12 at 15:51
  • Your code is OK, it should work. But I take notice that you use datetime doctrine mapping type for "myDate" field so better use datetime field type in "AddMyEntity" class http://symfony.com/doc/current/reference/forms/types/datetime.html – alexfv Jan 03 '12 at 17:18

4 Answers4

75

Set it in the entity constructor:

class Entity
{
    /**
     * @var \DateTime
     */
    private $date;

    public function __construct()
    {
        $this->date = new \DateTime();
    }
}
Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • As said in the question, if tried setting it as well as in the __construct as in the function MyEntity() without success. – i.am.michiel Jan 03 '12 at 15:50
  • Just to complete your suggestion, it actually works on simple types : text, ints and so on. It is not working on DateTime. – i.am.michiel Jan 03 '12 at 15:53
  • Hmm. I initialize `DateTime` objects in constructors and it works great. Probably something is wrong somewhere else in your app. – Elnur Abdurrakhimov Jan 03 '12 at 16:40
  • 1
    +1 @elnur: every time I search a Symfony2 related question lately, you've answered it. Thanks for that! :) – Darragh Enright May 04 '12 at 22:31
  • What did you do to get this working? I have the same problem. I'm using a form collection. – ncatnow Jun 14 '13 at 10:42
  • 1
    Based on: https://github.com/symfony/symfony/issues/5095 and https://github.com/symfony/symfony/pull/6910 it seems there is a limitation with using default values set in entity constructors in form collections. – ncatnow Jun 14 '13 at 10:54
  • Upvoted because it's better to add defaults which should be persisted in the __construct – Tomkay Nov 15 '13 at 13:15
  • In constructor only assign variables to fields, nothing else, no condition, no instantiate, nothing. Constructors should be code free. – vaso123 Sep 28 '19 at 23:57
35

Elnur's answer is correct and is perhaps the recommended one. But for completeness, an alternative way to set the default value for a date widget in a form is to specify the data key in the options array argument with an instance of DateTime.

$builder->add('myDate', 'date', array(
    'data' => new \DateTime()
));

Note: This will overwrite the previously set datetime on every edit.

Chris Bornhoft
  • 4,195
  • 4
  • 37
  • 55
Adam Elsodaney
  • 7,722
  • 6
  • 39
  • 65
  • 8
    This approach works only when adding new entry but fails when editing because it doesn't put database value but current time on the form – Masinde Muliro Mar 02 '14 at 03:32
  • @MasindeMuliro Correct. I added this answer here because the question was the first result in Google and there was a scenario I had where tests wouldn't pass by simply instantiating in the constructor. If I recall what the edge case was, I'll add it to the answer. – Adam Elsodaney Oct 08 '14 at 08:58
  • 1
    Thank you! This was a better solution for me. I needed to default to the date the user edited the record, not the date it was first created in the database. – Ben Hillier Jan 07 '16 at 09:29
  • Instead of `date` as second parameter I had to set `DateType::class` and add the use statement of `Symfony\Component\Form\Extension\Core\Type\DateType`. Thank you very much – Alberto Méndez Apr 23 '17 at 16:55
14

This solution doesn't require modifying your entity object.

    $builder->add('myDate', DateTimeType::class, [
        'label' => 'My Date',
        'required' => false,
        'date_widget' => 'single_text',
        'time_widget' => 'single_text',
        'date_format' => 'dd/MM/yyyy'
    ]);

    $builder->get('myDate')->addModelTransformer(new CallbackTransformer(
        function ($value) {
            if(!$value) {
                return new \DateTime('now +1 month');
            }
            return $value;
        },
        function ($value) {
            return $value;
        }
    ));

This solution applies the behaviour to just this form, it does not couple this behaviour to the entity itself. You might have several forms that modify an entity with different required behaviours. Some require a default date, others don't.

Henry
  • 7,721
  • 2
  • 38
  • 38
-8

You can set the attributes to on update CURRENT_TIMESTAMP and defualt to current time stamp will update the current time stamp automatically without updating through query

`feildname` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
Boopathi
  • 166
  • 5
  • 2
    As said in the question above, I'm trying to set a default value in a form. Not in database. I need to suggest a default value to the user not. – i.am.michiel Jan 03 '12 at 14:09