FOSUserBundle Unique Entity constraints

匆匆过客 提交于 2019-12-25 08:34:53

问题


I want to set up a unique constraint on the fields "username" and "email" but it doesn't work :

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Table(name="acteurs")
 * @ORM\Entity(repositoryClass="UserBundle\Repository\ActeurRepository")
 * @ORM\InheritanceType("JOINED")
 * @UniqueEntity(fields="email", message="Cet email existe déjà.")
 * @UniqueEntity(fields="username", message="Ce login existe déjà.")
 */
abstract class Acteur extends BaseUser { ... }

The form is validated by symfony and i get database error :

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicata du champ 'test@gmail.com' pour la clef 'UNIQ_B85835ACA0D96FBF'

What is wrong ?


回答1:


Sadly there is a bug in Symfony's Validation Component concerning UniqueEntity using with inherited classes. It's already reported in 2012: https://github.com/symfony/symfony/issues/4087

I've never tried it, but you can workaround it using the repositoryMethod-option.

/**
 * @ORM\Table(name="acteurs")
 * @ORM\Entity(repositoryClass="UserBundle\Repository\ActeurRepository")
 * @ORM\InheritanceType("JOINED")
 * @UniqueEntity(fields="email", message="Cet email existe déjà.", repositoryMethod="findByUniqueEmail")
 * @UniqueEntity(fields="username", message="Ce login existe déjà.", repositoryMethod="findByUniqueUsername)
 */
abstract class Acteur extends BaseUser { ... }

And add this to your ActeurRepository:

class ActeurRepository extends EntityRepository
{
    public function findByUniqueEmail(array $criteria)
    {
        return $this->findBy($criteria);
    }

    public function findByUniqueUsername(array $criteria)
    {
        return $this->findBy($criteria);
    }
}


来源:https://stackoverflow.com/questions/39773960/fosuserbundle-unique-entity-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!