我是 Symfony 2 Web 框架的新手,并且正在努力完成一项非常基本的验证任务。我有一个Post
包含 member 的实体模型,slug
我用它来建立帖子的链接。在Post.orm.yml
我定义unique: true
并希望将此约束作为验证器包含在内。
我创建了一个文件validation.yml
:
# src/OwnBundles/BlogpostBundle/Resources/config/validation.yml
OwnBundles\BlogpostBundle\Entity\Post:
properties:
slug:
- NotBlank: ~
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: slug
我的控制器中的创建功能非常简单:
public function addAction(Request $request)
{
$post = new Post();
$form = $this->createForm(new PostType(), $post);
if($request->getMethod() == 'POST')
{
$form->bind($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
return $this->redirect(
$this->generateUrl('own_bundles_blogpost_homepage')
);
}
}
return $this->render(
'OwnBundlesBlogpostBundle:Default:add.html.twig',
array(
'title' => 'Add new blogpost',
'form' => $form->createView(),
)
);
}
基本的页面流工作正常,我可以添加帖子并查看它们,但是如果我复制帖子标题来测试我的验证,它会引发异常:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'duplicate-slug' for key 'UNIQ_FAB8C3B3989D9B62'
. 我已经浏览了很长一段时间的文档,但我无法找出我的$form->isValid()
退货原因true
。