Symfony2集合字段by_reference = false与setter

时间:2012-10-31 22:27:21

标签: symfony collections arraycollection fieldtype

我有一个带标签字段的表单。 Tags是绑定实体上的Doctrine ArrayCollection。该字段是文档建议的by_reference = false,但是在添加新元素时,将表单绑定到实体会非法行为,如下所示:

$data=$entity->getTags(); //gets the ArrayCollection but does not care that it is not an array, and shoulrd be converted first
//do the value modifications like:
$data[]=new Tag(...);
$entity->setTags($data); //poor setter gets called with the already-updated collection, this operation is pointless

我认为by_reference false可以避免这个问题。如果是的话,那就是发生故障。如果没有,那么文档很可能有一个ArrayCollections的例子,但不关心这个非常残酷的对setter的忽视......

我应该使用什么?在getter中返回toArray()是不行的(显然,设计模型以便与糟糕的表单实现兼容是不合理的。是否有类似于'collection'的类型强制转换为数组?

1 个答案:

答案 0 :(得分:0)

将标记添加到实体中,因为它应该发生:

$new_tag = new Tag(...);
$entity->addTag($new_tag);

基本的Doctrine生成实体中没有集合的set-function。