本文介绍了Symfony2 Form Entity to String Transformer 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Symfony 2.1.3-DEV 并尝试完成将实体转换为字符串(某种 ID),然后在提交表单时从字符串转换回实体.如果我使用食谱中给出的变压器,问题是一样的:http://symfony.com/doc/master/cookbook/form/data_transformers.html

I am using Symfony 2.1.3-DEV and trying to accomplish transforming entity to string (ID of some kind) and then back from string to entity when form is submitted. The issue is the same if I'm using the transformer given in the cookbook:http://symfony.com/doc/master/cookbook/form/data_transformers.html

控制器代码:

$task = $entityManager->find('AcmeTaskBundle:Task', $id);
$form = $this->createForm(new TaskType(), $task); // so $task->issue is Issue object

我收到此错误:

表单的视图数据应该是类的一个实例Acme\TaskBundle\Entity\Issue,但是是一个(n)字符串.你可以避免这种情况通过将data_class"选项设置为 null 或添加视图来出错将一个(n)字符串转换为一个实例的转换器Acme\TaskBundle\Entity\Issue.

问题是,我已经有一个转换器,可以转换为字符串.

The thing is, that I already have a transformer, which transforms TO string.

来自 Form.php:

if (null !== $dataClass && !$viewData instanceof $dataClass) {
    throw new FormException(
       //...
    );
}

为什么 $viewData 被检查为 data_class 参数的实例(或给定对象的猜测类型)?视图数据不应该是字符串/数组等吗?我错过了什么吗?

Why $viewData is checked to be instance of data_class parameter (or the guessed type of given object)? Isn't view data supposed to be string/array etc.? Am I missing something?

推荐答案

经过一步一步的挖掘,我发现了我面临的问题.

After some digging step-by-step I found the problem that I was facing.

查看数据确实必须是data_class 参数指定的类的实例.如果您使用转换器对象 -> 字符串,则必须将 data_class 参数设置为 null.

View data indeed must be the instance of class specified by data_class parameter. If you are using transformer Object -> string, you must set the data_class parameter to null.

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => null,
    ));
}

默认情况下,data_class 是指定初始数据的 get_class 的结果.如果您将对象传递给控制器​​的 createForm 或一些相应的表单创建器函数,并且 data_class 的默认值不存在,它将被设置为给定对象的类.

By default, data_class is result of get_class of specified initial data. If you pass object to controller's createForm or some corresponding form-creator function, and no default value for data_class exists, it will be set to class of given object.

仍然,文档中给出的示例工作正常 - 如果表单是内部的(在另一个表单中),data_class 将不会被设置,因此它将是 null.

Still, the example given in the docs works fine - if form is inner (inside another form), data_class will not be set so it will be null.

由于仅从一个字段(我的转换器案例中的文本字段)制作表单是非常罕见的,通常这种带有转换器的表单会在其他表单中,所以它会正常工作.

As it's very rare to make form only from one field (text field in my transformer case), usually this form with transformer will be inside some other form, so it'll work fine.

这篇关于Symfony2 Form Entity to String Transformer 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 12:19