创建一个从 DateTime 对象到字符串的简单 DataTransformer 和一个名为 ie 'hidden_datetime' 的新表单类型,它使用新的 DataTransformer 并将隐藏的表单类型作为父级。
<?php
namespace YourProject\YourBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
class DateTimeToStringTransformer implements DataTransformerInterface
{
public function __construct()
{
}
/**
* @param \DateTime|null $datetime
* @return string
*/
public function transform($datetime)
{
if (null === $datetime) {
return '';
}
return $datetime->format('Y-m-d H:i:s');
}
/**
* @param string $datetimeString
* @return \DateTime
*/
public function reverseTransform($datetimeString)
{
$datetime = new \DateTime($datetimeString);
return $datetime;
}
}
..
<?php
namespace YourProject\YourBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;
use YourProject\YourBundle\Form\DataTransformer\DateTimeToStringTransformer;
class HiddenDateTimeType extends AbstractType
{
public function __construct()
{
}
public function getName()
{
return 'hidden_datetime';
}
public function getParent()
{
return 'hidden';
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new DateTimeToStringTransformer();
$builder->addModelTransformer($transformer);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
parent::setDefaultOptions($resolver);
$resolver->setDefaults(array(
));
}
}
在 services.yml 中将新的“hidden_datetime”表单类型注册为服务
yourproject.hidden_datetime.form.type:
class: YourProject\YourBundle\Form\Type\HiddenDateTimeType
tags:
- { name: form.type, alias: hidden_datetime }
然后可以在您的表单中使用新的 hidden_datetime 类型:
// 在我的类类型中
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('createdAt','hidden_datetime')
->add('comment','textarea')
;
}