2012-09-26 85 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