2012-09-26 62 views
14

我是Symfony 2 web框架的新手,我正在努力完成一个非常基本的验证任务。我有一个实体模型Post,它有一个成员slug,我用它来建立到帖子的链接。在Post.orm.yml中,我定义了unique: true,并且希望将此约束作为验证程序。YML验证文件被忽略

我创建了一个文件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

回答

33

您是否在app/config/config.yml中启用了验证?

... 

framework: 
    ... 
    validation: { enabled: true } 
    ... 

... 

,如果要定义与注释验证过,你必须既能够验证和注解验证:

... 

framework: 
    ... 
    validation: { enabled: true, enable_annotations: true } 
    ... 

... 

然后不要忘记清除app/cache目录。

+1

我的config.yml说:'framework:validation:{enable_annotations:true}';我认为这使验证 - 我错了......感谢您的快速帮助,我不知道为什么我找不到这个。 – nijansen

+0

如果你也想使用注释,你必须使用这两个参数。我编辑了我的答案。 – AlterPHP

+0

谢谢,我相应地更新了我的配置。现在它像一个魅力。 – nijansen