Php 将DataTime字段拆分为两个字段的表单
我想使用Symfony 2.3将DateTime字段拆分为两个字段(日期和时间)。因此,我尝试调整找到的Symfony 2.0解决方案,并对Symfony 2.3进行了必要的更改 新类型:Php 将DataTime字段拆分为两个字段的表单,php,symfony,symfony-2.3,Php,Symfony,Symfony 2.3,我想使用Symfony 2.3将DateTime字段拆分为两个字段(日期和时间)。因此,我尝试调整找到的Symfony 2.0解决方案,并对Symfony 2.3进行了必要的更改 新类型: class MyDateTimeType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('date'
class MyDateTimeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date', 'date', array(
'label' => 'label.form.date',
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'yyyy-MM-dd',
'error_bubbling' => true
))
->add('time', 'time', array(
'label' => 'label.form.time',
'input' => 'datetime',
'widget' => 'single_text',
'error_bubbling' => true
))
->addViewTransformer(new DateTimeToDateTimeArrayTransformer());
}
public function getDefaultOptions(array $options)
{
return array(
'label' => 'label.form.date',
'error_bubbling' => false
);
}
public function getParent()
{
return 'form';
}
public function getName()
{
return 'my_datetime';
}
}
和数据转换器:
class DateTimeToDateTimeArrayTransformer implements DataTransformerInterface
{
public function transform($datetime)
{
if ($datetime instanceof \DateTime)
{
$date = clone $datetime;
$date->setTime(12, 0, 0);
$time = clone $datetime;
$time->setDate(1970, 1, 1);
}
else
{
$date = null;
$time = null;
}
$result = array(
'date' => $date,
'time' => $time
);
return $result;
}
public function reverseTransform($array)
{
$date = $array['date'];
$time = $array['time'];
if(null == $date || null == $time)
return null;
$date->setTime($time->format('G'), $time->format('i'));
return $date;
}
}
服务.yml
foo.bar.form.type.my_date_time:
class: Foo\Bar\Form\MyDateTimeType
tags:
- { name: form.type, alias: my_datetime }
但是当我在这样的表单中使用类型时:
$builder->add('abc', 'my_datetime', array(
'label' => 'ABC',
'data' => new \DateTime(null, new \DateTimeZone('UTC'))
));
我得到一个错误:
表单的视图数据应该是类DateTime的实例,但我需要一个(n)数组。您可以通过将“data_class”选项设置为null或添加将(n)数组转换为DateTime实例的视图转换器来避免此错误。我知道有点晚,但我遇到了相同的问题并解决了它 您不需要新的表单类型来拆分日期时间字段的日期和时间 以你的形式
$builder
->add('datetime', DateTimeType::class, array(
'date_widget' => 'single_text',
'time_widget' => 'single_text',
'date_format' => 'dd.MM.yyyy',
'required' => true,
))
:
如果要单独呈现输入字段(例如添加不同的类作为属性),只需在twig模板中执行此操作
{{ form_start(form) }}
..
{{ form_widget(form.datetime.date) }}
{{ form_widget(form.datetime.time) }}
..
{{ form_end(form) }}
在Symfony 2.6中测试,应该从2.3开始工作(甚至可能是2.1)
编辑:针对Symfony 2.8及更高版本进行了调整Perfect,使我免于创建可怕的解决方案