如何使symfony表单支持datetime本地输入类型


How to make symfony forms support datetime-local input type?

大多数浏览器都放弃了对datetimedatetime-local作为有效输入类型的支持。截至撰写本问题时,对datetime-local的支持多于对datetime的支持(后者几乎不存在)。

如果使用Symfony的表单生成器构建表单,它支持datetime,但不支持datetime-local。那么,如何让symfony表单生成器接受datetime-local输入类型,并保持输入类型的其余功能不变呢?

解决这个问题的一种方法是,如果我们可以将输入类型的文本更改为datetime-local,这可以通过覆盖DateTimeType并使用它来完成。

<?php
namespace AppBundle'Component'Form'Extension'Core'Type;
use Symfony'Component'Form'FormInterface;
use Symfony'Component'Form'FormView;
class DateTimeType extends 'Symfony'Component'Form'Extension'Core'Type'DateTimeType
{
    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['widget'] = $options['widget'];
        // Change the input to a HTML5 datetime input if
        //  * the widget is set to "single_text"
        //  * the format matches the one expected by HTML5
        //  * the html5 is set to true
        if ($options['html5'] && 'single_text' === $options['widget'] && self::HTML5_FORMAT === $options['format']) {
            $view->vars['type'] = 'datetime-local';
        }
    }
}