Thomas Fournet
Thomas Fournet

Reputation: 700

Symfony can't access entity repository from Listener

I have a Listener where I can insert data in the database but I can't access my custom method (countByUsername) in my User repository. However the part of UserTransfer which is commented (which does the same as the repository method) does work if I uncomment it.

UserTransfer.php

<?php

namespace PortalBundle\EventListener;

use PortalBundle\PortalBundle;
use Doctrine\ORM\OptimisticLockException;
use Symfony\Component\Security\Core\Event\AuthenticationEvent;
use PortalBundle\Entity\User;

class UserTranfer
{
    protected $em;

    public function __construct(\Doctrine\ORM\EntityManager $em)
    {
        $this->em=$em;
    }

    public function transfer(AuthenticationEvent $event){
        $token = $event->getAuthenticationToken();
        $user = $token->getUser();
        $repository = $this->em->getRepository('PortalBundle:User');
        $count = $repository->countByUsername($user->getUsername());

        /*$qb = $repository->createQueryBuilder('u');
        $qb->select('count(u._id)');
        $qb->where('u._username = :username');
        $qb->setParameter('username', $user->getUsername());
        $count=$qb->getQuery()->getSingleScalarResult();*/

        if($count !== "0") {
            return;
        }
        $newUser = new User();
        $newUser->setUsername($user->getUsername())->setFullname($user->getFullname());
        $this->em->persist($newUser);
        try {
            $this->em->flush();
        } catch (OptimisticLockException $e) {
        }
    }
}

UserRepository.php

<?php

namespace PortalBundle\Repository;

class UserRepository extends \Doctrine\ORM\EntityRepository
{
    public function countByUsername($username)
    {
        $qb = $this->createQueryBuilder('u');
        $qb->select('count(u._id)');
        $qb->where('u._username = :username');
        $qb->setParameter('username', $username);

        return $qb->getQuery()->getSingleScalarResult();
    }
}

The very beginning of User.php

<?php

namespace PortalBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * User entity
 * @ORM\Entity(repositoryClass="PortalBundle\Repository\UserRepository")
 * @ORM\Table(name="user")
 * @ORM\Entity
 */
class User
{

The error which is returned id Undefined method 'countByUsername'. The method name must start with either findBy or findOneBy!

Upvotes: 1

Views: 725

Answers (1)

fxbt
fxbt

Reputation: 2596

In your User class, you defined the ORM\Entity annotation twice.

The last one is the one parsed by Doctrine and it's missing the repository.

This will work:

/**
 * User entity
 * @ORM\Entity(repositoryClass="PortalBundle\Repository\UserRepository")
 * @ORM\Table(name="user")
 */
class User
{

Upvotes: 1

Related Questions