2

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

1
  • The tags created in reverseTransform(), how do they know to which Post object they belong to? I have a similar implementation with tags. They get loaded properly as a comma-separated list, but when saving, they get saved without their "post_id".. How can you pass the "post id" all the way to this transformer??.. Commented Feb 4, 2012 at 21:33

1 Answer 1

2
+500

It looks like in your reverseTransform() method, you're searching for a single tag with this line:

$tag = $this->em->getRepository('JM\BlogBundle\Entity\Tag')->findBy(array('name' => $strTag));

However, findBy() will always return an ArrayCollection, even if only one result is found. Try using findOneBy(), 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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.