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.

2 comments:

  1. Hi Robert,

    Thank you for sharing. I have similar problem too, but the __sleep method did not work for me ...

    A have this :
    Group -OneToMany-> Company -OneToOne-> User

    It failed one my side because if the OneToMany relationship (maybe due to the 2nd top level relationship)

    ReplyDelete
  2. Hello Nicolas,
    Did you tried to add the __sleep method for the Group entity too?

    If you find an answer please post it here so others who have the same problem would find it.

    ReplyDelete