我有一个User类,如下所示:
/**
* User
*
* @ORM\Table()
* @ORM\Entity
* @UniqueEntity("username")
*/
class User implements UserInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=30, unique=true)
*/
private $username;
...
正如您猜测的那样,我希望保持用户名的独特性。当我尝试注册一个复制以前用户名的新用户时,我得到一个数据库异常:
An exception occurred while executing 'INSERT INTO User (username, hashedpassword, email) VALUES (?, ?, ?)' with params ["xx", "$2y$10$7rrY0tw0eG8ui7hRkpGI..8Wf16DP1fQMLymaOmHnbZsBw6M1uY.i", "ddsds@u.com"]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'xx' for key 'UNIQ_2DA17977F85E0677'
我认为可能问题出在我的注册管理器中。我正在使用
上给出的那个http://symfony.com/doc/current/cookbook/doctrine/registration_form.html
相关位:
class AccountController extends Controller
{
public function registerAction()
{
$registration = new Registration();
$form = $this->createForm(new RegistrationType(), $registration, array(
'action' => $this->generateUrl('account_create'),
));
return $this->render(
'RezialRezialBundle:Account:register.html.twig',
array('form' => $form->createView())
);
}
public function createAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new RegistrationType(), new Registration());
$form->handleRequest($request);
if ($form->isValid()) {
$registration = $form->getData();
//should I manually check for unicity here?
$em->persist($registration->getUser());
$em->flush();
//The following 3 lines make the user automatically login
//upon successfull registration!
$user = $registration->getUser();
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
return $this->redirectToRoute('homepage');
}
return $this->render(
'RezialRezialBundle:Account:register.html.twig',
array('form' => $form->createView())
);
}
}
关于缺少什么的任何想法?
答案 0 :(得分:2)
您是否忘记了注册类的$ user属性中的 @Assert \ Valid()注释?
此约束用于启用对象的验证 嵌入作为要验证的对象的属性。这可以让你 验证对象及与之关联的所有子对象。
答案 1 :(得分:1)
试试这个:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="user")
* @UniqueEntity(fields="username", message="Username is already taken.")
*/
class User
{
/**
* @ORM\Column(name="username", type="string", length=30, unique=true)
*/
protected $username;
}