【问题标题】:How to make symfony forms support datetime-local input type?如何使 symfony 表单支持 datetime-local 输入类型?
【发布时间】:2016-03-31 10:37:57
【问题描述】:
大多数浏览器都不再支持datetime 和datetime-local 作为有效输入类型。在撰写此问题时,对datetime-local 的支持比对datetime 的支持要多(几乎不存在)。
如果您使用 Symfony 的表单构建器构建表单,它支持 datetime 但不支持 datetime-local。那么如何让 symfony 表单构建器接受 datetime-local 输入类型并保持输入类型的其余功能相同?
【问题讨论】:
标签:
php
html
datetime
symfony
formbuilder
【解决方案1】:
解决此问题的一种方法是,如果我们可以将输入类型的文本更改为 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';
}
}
}