52

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;
3
  • Please show definition of the property "myDate" in class "MyEntity" and method "buildForm" of form type class "AddMyEntity". Commented Jan 3, 2012 at 15:04
  • The second part of my question is a extract of the buildForm method. And I'll add the entity part. Commented Jan 3, 2012 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 symfony.com/doc/current/reference/forms/types/datetime.html Commented Jan 3, 2012 at 17:18

4 Answers 4

74

Set it in the entity constructor:

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

    public function __construct()
    {
        $this->date = new \DateTime();
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

As said in the question, if tried setting it as well as in the __construct as in the function MyEntity() without success.
Just to complete your suggestion, it actually works on simple types : text, ints and so on. It is not working on DateTime.
Hmm. I initialize DateTime objects in constructors and it works great. Probably something is wrong somewhere else in your app.
+1 @elnur: every time I search a Symfony2 related question lately, you've answered it. Thanks for that! :)
Based on: github.com/symfony/symfony/issues/5095 and github.com/symfony/symfony/pull/6910 it seems there is a limitation with using default values set in entity constructors in form collections.
|
36

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.

4 Comments

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
@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.
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.
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
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.

Comments

-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

1 Comment

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.

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.