我是Symfony 2 Web框架的新功能,并且正在努力进行非常基本的验证任务.我有一个实体模型Post有一个成员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]:完整性约束违规:1062重复条目“重复插入”键’UNIQ_FAB8C3B3989D9B62′.我一直在扫描文档已经有一段时间了,但是我无法找出为什么我的$form-> isValid()返回true.