Sunday, May 6, 2012

Symfony2 many-to-many self referencing relation using Doctrine2

Symfony2 many-to-many self referencing relation using Doctrine2

 Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

I created this blog because I wanted to help others who are self learners like me. I spent few hours to figure out why I was getting the next error when playing with Symfony2.
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken::serialize() must return a string or NULL

I had an User entity a many to many self referencing relation. I still did not find out why I was getting the error but I found out here a way to get rid of the error. I just had to add the __sleep method for the user entity like this:

/**
 * @ORM\Entity(repositoryClass="Acme\DemoBundle\Repository\UserRepository")
 * @ORM\Table(name="users")
 * @ORM\HasLifecycleCallbacks()
 */

 class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    ..................
    public function __sleep()
    {
        return array('id');
    }
}

I hope this helped someone who got the same error as I did. If you have a better solution please post it here.