我需要一个接受字符串或 DateTime 对象作为输入的自定义字段。经过一番讨论,我决定 DataTransformers 是要走的路。我按照Cookbook上的说明进行操作,但出现以下错误:
可捕获的致命错误:传递给 Symfony\Component\Form\FormFactory::loadTypeExtensions() 的参数 1 必须实现接口 Symfony\Component\Form\FormTypeInterface,给出 Yanic\HomeBundle\Form\DataTransformer\DateToStringTransformer 的实例,在 /Applications/MAMP 中调用/htdocs/symfony-standard-2.1/vendor/symfony/symfony/src/Symfony/Component/Form/FormFactory.php 在第 320 行并在 /Applications/MAMP/htdocs/symfony-standard-2.1/vendor/symfony/symfony 中定义/src/Symfony/Component/Form/FormFactory.php 第 332 行
似乎它需要一个 FormType,但文档说这不应该是必要的。
这就是我正在使用的代码:
用户类型.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$transformer = new \Yanic\HomeBundle\Form\DataTransformer\DateToStringTransformer();
$builder
->add('username')
->add('password','password',
array(
'required' => false
))
->add('email')
->addViewTransformer( $transformer )
->add('created', 'datetimeToString', array(
'disabled' => true,
))
->add('modified', 'datetimeToString', array(
'disabled' => true,
))
->add('isActive', null, array(
'label' => 'Is active?',
'required' => false
))
->add('lastLogin', null, array(
'empty_data' => 'never',
'widget' => 'single_text',
'read_only' => true,
'label' => 'Last login'
))
->add('modifiedBy', null, array(
'label' => 'Modified by',
'read_only' => true
))
->add('groups')
;
}
DateToStringTransformer.php
namespace Yanic\HomeBundle\Form\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class DateToStringTransformer implements DataTransformerInterface
{
/**
* Transforms an DateTime object to a string.
*
* @param \DateTime|null $issue
* @return string
*/
public function transform($date)
{
if (null === $date) {
return "never";
}
return $date->format('d-m-Y H:i');
}
/**
* Transforms a string (date formatted) to an object (\DateTime).
*
* @param string $date
* @return \DateTime|null
* @throws TransformationFailedException
*/
public function reverseTransform($number)
{
return $number;
}
}
服务.yml
services:
form.dataTransformer.datetimeToString:
class: Yanic\HomeBundle\Form\DataTransformer\DateToStringTransformer
tags:
- { name: form.type, alias: datetimeToString }
我究竟做错了什么?
啊,我用的是 Symfony 2.1 Beta2