简体   繁体   中英

SYMFONY Form TimeType use 1970-01-01 as default date, what is the value to set in the constraint GreaterThanOrEqual?

I have a TimeType field in a Symfony form. In the form AbstractType extended class the field looks like this:

    $form->add('fieldTime', TimeType::class, array(
        'label' => myLabel,
        'constraints'=>array(
            new GreaterThanOrEqual(array('value'=>date('H:i'))),
            new Time()
        ),
    );

The problem is that date('H:i') set as value to compare in the constraint GreaterThanOrEqual , pick up the actual date like: 2016-02-14 10:15:00 .

Whereas the value received on the Submit is like this:

DateTime {#12481 ▼
  +"date": "1970-01-01 11:00:00.000000"
  +"timezone_type": 3
  +"timezone": "Europe/Paris"
}

As you see, it has the time selected by the user but with the 1970 date, hence the constraint is always false .

I wonder how to either:

  • Pass in the constraint GreaterThanOrEqual value a time with the 1970-01-01 date but with the actual time;
  • Or how to use the default today date with the time submitted by the user thru the form?

You can pass "today" to GreaterThanOrEqual , and use a new DateTime() to get the complete date, not just the time of the day:

$form->add('fieldTime', TimeType::class, array(
    'label' => myLabel,
    'constraints'=>array(
        new GreaterThanOrEqual("today")
    ),
    'data' => new DateTime(),
);

Note that "today" is using the server's configured timezone. If you want to specify it, append it to the date string, ie "today UTC"

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