2013-05-06 55 views
0

我在Symfony 2.2中遇到了那些驗證約束的問題。爲什麼不考慮Symfony2驗證約束?

「username」和「pass」的驗證約束似乎沒有考慮在內。但是「UniqueEntity」約束起作用。

我不認爲我在yaml語法中犯了錯誤。

這是陽明語法:

Fastre\PhpFtpAdminBundle\Entity\Account: 
properties: 
    username: 
     - Regex: {pattern: "/[a-zA-Z0-9]+/", message: Le nom d'utilisateur ne peut contenir que des lettres minuscules et majuscules et des chiffres.} 
    pass: 
     - Length: {min: 8, minMessage: "Your name must have at least {{ limit }} characters."} 
constraints: 
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: {fields: [username], groups: [registration]} 

和Controller:

if ($request->getMethod() === 'POST') { 

     $form->bind($request); 

     $data = $form->getData(); 



     $errors = $this->get('validator')->validate($data, array('Default')); 

     //throw new \Exception($errors->count()); 

     if ($errors->count() == 0) { //the errors->count() is always set to 0! 
      $em->flush(); 

      //TODO: i18n 
      $this->get('session') 
        ->getFlashBag() 
        ->add('notice', 'Compte '.$account->getUsername().' modifié'); 

      return $this->redirect($this->generateUrl('account_list')); 

     } else { 


      foreach ($errors as $error) { 
       $this->get('session') 
        ->getFlashBag() 
        ->add('warning', $error->getMessage()); 
      } 

      return $this->render('FastrePhpFtpAdminBundle:Accounts:form.html.twig', 
       array(
        'form' => $form->createView(), 
        'action_path' => $this->generateUrl('account_view', array('id' => $id)) 
        ) 
       ); 
     } 

    } 

回答

4

做這件事時:

$errors = $this->get('validator')->validate($data, array('Default')); 

您驗證只有驗證組Default。但是,你的UniqueEntity限制只適用於registration組,因爲你的設置:

{fields: [username], groups: [registration]} 

所以,你可以刪除該組的UniqueEntity驗證或像第二個電話驗證它:

$errors = $this->get('validator')->validate($data, array('registration')); 

附註中,不是:

$form->bind($request); 
    $data = $form->getData(); 
    $errors = $this->get('validator')->validate($data, array('Default')); 
    if ($errors->count() == 0) { 
     //do your stuff 
    } 

我會強烈建議使用一些更簡單:

$form->bind($request); 

    if ($form->isValid()) { 
     // do your stuff 
    } 

以及在這種情況下,組生效,請參考:

http://symfony.com/doc/current/book/forms.html#book-forms-validation-groups

+0

你是對的。我認爲這是一個「默認」驗證組,我認爲我使用它。 – 2013-05-08 12:40:47

+0

我認爲不可能對驗證組進行表單驗證。我認爲代碼'$ form-> isValid(array('registration'));'不管用。不是嗎? – 2013-05-08 12:41:29

+0

你說得對。如果你想爲你的表單進行驗證組,你必須在你的表單類型'setDefaultOptions()'中設置組,或者如果你不使用表單類型,在'createFormBuilder()'調用中。 – cheesemacfly 2013-05-08 14:01:28