I have setup a Symfony 2 Data Transformer that will allow the user to enter a comma separated list of string and convert that to an ArrayCollection which Doctrine expects. Now the problem is in the transform() where it will convert an ArrayCollection to a comma separated string.
/**
* Transform ArrayCollection of Tag's into Comma Separated string
*
* @param ArrayCollection $tags
* @return string
*/
public function transform($tags) {
if ($tags == null)
return '';
$tagNames = array();
var_dump($tags);
$tags->map(function($tag) use(&$tagNames) {
$tagNames[] = $tag->getName();
});
return implode(', ', $tagNames);
}
$tags look like:
object(Doctrine\Common\Collections\ArrayCollection)#222 (1) {
["_elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
array(1) {
[0]=>
array(1) {
[0]=>
object(JM\BlogBundle\Entity\Tag)#53 (3) {
["id":"JM\BlogBundle\Entity\Tag":private]=>
int(1)
["name":"JM\BlogBundle\Entity\Tag":private]=>
string(4) "blog"
["description":"JM\BlogBundle\Entity\Tag":private]=>
string(0) ""
}
}
}
}
Notice its an array in an array. Why is that?
UPDATE: data transformer code -> http://pastie.org/3004780
It looks like in your
reverseTransform()method, you’re searching for a single tag with this line:However,
findBy()will always return an ArrayCollection, even if only one result is found. Try usingfindOneBy(), which will simply return the result without the ArrayCollection wrapper.Also, for some prior art, check out the FPNTagBundle and Taggable Doctrine Extension. In particular, the TagManager might have some optimizations that you can implement in your own code.