I want to split a DateTime field into two fields (date and time) using Symfony 2.3. Therefore I tried to adapt the Symfony 2.0 solution found here and made the necessary changes for Symfony 2.3.
the new type:
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';
}
}
and the DataTransformer:
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;
}
}
services.yml
foo.bar.form.type.my_date_time:
class: Foo\Bar\Form\MyDateTimeType
tags:
- { name: form.type, alias: my_datetime }
But when I use the type in a form like this:
$builder->add('abc', 'my_datetime', array(
'label' => 'ABC',
'data' => new \DateTime(null, new \DateTimeZone('UTC'))
));
I get the error:
The form's view data is expected to be an instance of class DateTime, but i a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of DateTime.