Symfony2 collection field by_reference=false vs. setter

1.3k views Asked by At

I have a form with a field for tags. Tags is a Doctrine ArrayCollection on the bound entity. The field is by_reference=false as the doc suggested, but binding the form to the entity behaves illegally while adding new element, like this:

$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

I figured that by_reference false was there to avoid this problem. If yes, then it's malfunctioning. If not, then the doc is very poor having an example for ArrayCollections but not caring about this very brutal neglection of setters...

What should I use instead? Returning a toArray() in getter is a no-go (obviouly it's not sane to design the model for compatibility with poor form implementation. Is there perhaps a type similar to 'collection' that forces conversion to array?

1

There are 1 answers

3
Mats Rietdijk On

Add the tag to the entity as its supposed to happen:

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

There is no set-function for collections in a basic Doctrine generated entity.