tolgap
tolgap

Reputation: 9778

ReflectionException: Class ArrayCollection does not exist

I am trying to serialize entities for mobile digest. I have this Entity class:

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;

/**
 * xxx\xxx\Entity\User
 *
 * @ORM\Table()
 * @ORM\Entity()
 * @ORM\Entity(repositoryClass="xxx\xxx\Entity\UserRepository")
 */
class User extends BaseUser
{
    /**
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="\xxx\xxx\Entity\Music", mappedBy="user")
     */
    protected $musics;

    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="\xxx\xxx\Entity\Message", mappedBy="user")
     */
    protected $messages;

    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="\xxx\xxx\Entity\Location", mappedBy="user")
     */
    protected $locations;

    public function __construct()
    {
        parent::__construct();
        $this->musics = new ArrayCollection();
        $this->messages = new ArrayCollection();
        $this->locations = new ArrayCollection();
    }
}

Now when I call this line in my DefaultController.php:

$user = $this->getUser();
$em = $this->getDoctrine()->getManager();

$array = $em->getRepository('xxxBundle:User')
    ->findLatest();

$serializer = $this->get('serializer');
$response = $serializer->serialize($array, 'json'); //THIS LINE THROWS EXCEPTION

I have use Doctrine\Common\Collections\ArrayCollection; in DefaultController.php, but it seems the error is coming from inside JMSSerializerBundle.

What have I tried thusfar

The classes were autogenerated with app/console.

Upvotes: 2

Views: 3498

Answers (2)

anyapps
anyapps

Reputation: 99

This solution works! I am using JMSSerializerBundle and in Serialized Entity i have ManyToOne relation. I used property $product and of course setter and getter for that. If serializer try to get Product I got this same message i thnk because it don't understand how to convert related Entity to string/int. I adding Accessor with custom method getProductId and inside this method return

$this->product->getId()

JMS\Serializer\Annotation as Serializer @Serializer\Accessor(getter="getProductId")

In OneToMany relation, in custom get method I return ArrayCollection as Array $this->statuses->toArray()

You can also think of coonverter for relation entity, but I haven't tried (no time)

Upvotes: 0

vinnylinux
vinnylinux

Reputation: 7034

Take a look at this issue on GitHub: https://github.com/schmittjoh/JMSSerializerBundle/issues/123

Upvotes: 2

Related Questions