向EntityType字段添加选项“全选”将返回错误“无法反转属性路径的值”

时间:2017-03-08 10:50:34

标签: php forms symfony symfony-forms

我有一个带有EntityType字段的表单,用于检索酒店列表。

我想在该列表中添加一个选项“全选”以直接获取所有酒店的列表。

我创建了一个EntityTypeExtension(我现在更喜欢自定义扩展类型),其中包含以下内容:

public function finishView(FormView $view, FormInterface $form, array $options)
{
    $list = $this->em->getRepository($options['class'])->findAll();
    $new_choice = new ChoiceView($list, 'all', 'Select all'); // <- new option
    $view->vars['choices'][] = $new_choice;//<- adding the new option
}

这样可行,但如果我选择“全选”,我会得到以下堆栈:

Symfony\Component\Validator\ConstraintViolation

Object(Symfony\Component\Form\Form).children[hotel] = all

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException

Unable to reverse value for property path "[hotel]": The choice "all" does not exist or is not unique

Caused by:
Symfony\Component\Form\Exception\TransformationFailedException

The choice "all" does not exist or is not unique

我假设DataTransformer无法识别“all”选项。

你知道吗?我应该重载EntityType DataTransformer吗?

1 个答案:

答案 0 :(得分:0)

您需要在表单类型选项中添加multiple => true以允许自动转换ID数组(假设您的实体有一组酒店)或者您需要实现自己的数据转换器(这是相当简单)。

在您的情况下,您需要一个视图转换器

数据转换器doc:http://symfony.com/doc/current/form/data_transformers.html

我认为ChoiceView构造函数的value参数(第二个参数)应该是$list中对象的id的数组,因为EntityType期望choice的值是一个对象id。