好的,我知道这已被问了一百万次,但是这里有。
我已阅读this,this,this以及the docs,但仍无法弄清楚我的问题是什么。每当我尝试添加具有重复用户名/电子邮件的用户时,我都会收到异常,而不是预期的表单验证错误。我有一个SystemUser实体,通过连接继承映射链接到各种其他用户类型。在SystemUser类中,我有这个......
/**
* SystemUser
*
* @ORM\Table(name="systemuser")
* @ORM\Entity(repositoryClass="MyBundle\MainBundle\Entity\Repository\SystemUserRepository")
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="discr", type="integer")
* @ORM\DiscriminatorMap({"0" = "SystemUser", "1" = "SchoolAdmin", "2" = "Teacher", "3" = "Student", "4" = "Guardian", "5" = "SystemAdmin"})
* @ORM\HasLifecycleCallbacks()
* @UniqueEntity(fields={"email"}, message="This email address is already used in the system", groups={"registration"})
* @UniqueEntity(fields={"username"}, message="This cellphone number is already used in the system", groups={"registration"})
*/
在字段本身(电子邮件,用户名)上我还有unique=true
。我试过没有它,同样的例外。我也试过没有groups={"registration"}
标志,我不确定是否必须指定'注册'组并在某处声明(我确实检查过文档但找不到任何内容)。事实上,我不知道验证组在这个例子中实际上有什么用处,但我还是试过了。
在那里失败,我开始尝试validation.yml ......
MyBundle\MainBundle\Entity\SystemUser:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: email
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: username
properties:
email:
- Email: { groups: [registration] }
password:
- NotBlank: { groups: [registration] }
- Length: { min: 7, groups: [registration] }
cellphone:
- NotBlank: { groups: [registration] }
显然,没有结果。如果失败了,我继续使用表单类的setDefaultOptions()
方法。
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MyBundle\MainBundle\Entity\SystemUser',
'validation_groups' => array('registration'),
'cascade_validation' => true,
'constraints' => array(
new UniqueEntity(array(
'fields' => array('email')
)),
new UniqueEntity(array(
'fields' => array('username')
))
)
));
}
另外,没有任何运气。目前我将所有这3个活跃在一起,但仍然没有。我分别尝试了所有这些,但又一次,没有运气。
如果有人能指出这里发生了什么,我将不胜感激。现在已经挣扎了大约6个小时。
谢谢!
答案 0 :(得分:-1)
您应该尝试替换:
/**
* @UniqueEntity(fields={"email"}, message="This email address is already used in the system", groups={"registration"})
* @UniqueEntity(fields={"username"}, message="This cellphone number is already used in the system", groups={"registration"})
*/
由此:
/**
* @UniqueEntity(fields={"email", "username"}, message="A user with those email and username already exists", groups={"registration"})
*/
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: email
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: username
由此:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
- email
- username
'constraints' => array(
new UniqueEntity(array(
'fields' => array('email')
)),
new UniqueEntity(array(
'fields' => array('username')
))
)
由此:
'constraints' => array(
new UniqueEntity(array(
'fields' => array('email', 'username')
))
)