Symfony4 DateTimeType显示无效日期

时间:2018-05-17 08:56:42

标签: symfony datetime

我不明白为什么要通过Symfony Forms创建DayTimePicker控件:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('start', DateType::class, array(
            'attr' => array(
            ),
            'data' => new DateTime('last day of previous month')
        ))

        ->add('end', DateType::class, array(
            'attr' => array(
            ),
            'data' => new \DateTime("now")
        ))

        ->add('submit', SubmitType::class, array('attr' => array('label' => 'Generate'))
    ;
}

收到选择日期2018年4月31日因为选择此日期并发送表格这个日期甚至没有通过验证,所以为什么会生成?

1 个答案:

答案 0 :(得分:1)

您需要告诉DateTime如何设置日期格式。试试:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('start', DateType::class, array(
            'attr' => array(
            ),
            'widget' => 'single_text',
            'data' => new DateTime('last day of previous month')->format('Y-m-d')
        ))

        ->add('end', DateType::class, array(
            'attr' => array(
            ),
            'widget' => 'single_text',
            'data' => new \DateTime("now")->format('Y-m-d')
        ))

        ->add('submit', SubmitType::class, array('attr' => array('label' => 'Generate'))
    ;
}