Symfony:如何在FormFactory中使用数据转换器?

问题描述

在我的Symfony应用程序中,我有一个From,其中包含许多复选框,单选框,文本字段以及DateTime对象。 除DateTime对象之外的所有东西都可以正常工作,但是有了它们,我总是会收到错误"Object of class DateTime Could not be converted to string" 因此,我想使用this tutorial将datetime对象更改为字符串。


问题是我正在使用FormFactory,而当我使用addModelTransformer()-Method这样的方法时……

一个选项:

$form->add($formFactory->createNamed('value','date',null,$fieldOptions));
$form->get('value')->addModelTransformer(new CallbackTransformer(
    function($dateAsDate){
        return $dateAsDate->format('Y-m-d');
    },function ($dateAsstring){
        return "test"; //Todo: to be changed to make string to date
    }
));

...我收到错误"Call to undefined method Symfony\Component\Form\Form::addModelTransformer() "


当我像这样在Formfactory外部使用构建器功能时...

第二个选项:

//$builder->addEventListener Stuff is above

$builder->get('value')->addModelTransformer(new CallbackTransformer(
   function($dateAsDate){ return $dateAsDate->format('Y-m-d'); },function ($dateAsstring){ return 'null'; } //Todo: to be changed to make string to date
));

...我收到错误"The child with the name "value" does not exist."


有人知道如何进行这项工作吗?

解决方法

这里不需要使用任何自定义的Tranformer。

DateType字段本身可以正确处理DateTime对象。 您可能要指定一些选项,例如'format'和'widget',具体取决于您要如何渲染字段,但是默认的'input'应该可以在DateTime上正常工作。 例如:

$builder->add('value',DateType::class,[
    'format' => 'y-MM-dd','widget' => 'single_text',// To have a single input text box
    'input' => 'datetime'      // This is the default value
];