2014-09-06 94 views
-1

我將數據保存到數據庫之前驗證我的數據,但到目前爲止,當關閉javascript驗證時,我無法檢測對象是否有效。下面是我如何做它:symfony2 isValid()方法總是返回true

$editForm = $this->createEditForm($post, $category_id, $section_id, $topic_id); 
     $editForm->handleRequest($request); 

if ($editForm->isValid()) { 
      $em->flush(); 
      return $this->redirect($this->generateUrl('topic_show', array('category_id'=> $category_id, 'section_id'=> $section_id, 'id'=> $topic_id))); 
     } 

可惜的方法IsValid()返回true,每次,然後我從MySQL得到錯誤。

我嘗試了不同的方法,從here

$validator = $this->get('validator'); 
      $errors = $validator->validate($post); 

     if (count($errors) > 0) { 
       throw $this->createNotFoundException('Unable to find Post entity.'); 
      /* 
      * Uses a __toString method on the $errors variable which is a 
      * ConstraintViolationList object. This gives us a nice string 
      * for debugging 
      */ 
      $errorsString = (string) $errors; 

      return new Response($errorsString); 
     } 

採取但它也沒有工作......

UPDATE

我的 '內容' 屬性,它導致錯誤

/** 
    * @var string 
    * 
    * @ORM\Column(name="content", type="text") 
    */ 
    private $content; 
+0

你有什麼['Constraints'(http://symfony.com/doc/current/book/validation.html#basic-constraints) '或'FormType'? – 2014-09-06 19:03:08

+0

不,它看起來像在symfony中,默認情況下需要任何屬性 – Leo 2014-09-06 19:05:38

+0

不,您必須使用['NotBlank()'](http://symfony.com/doc/current/reference/constraints/NotBlank.html)或['NotNull()'](http://symfony.com/doc/current/reference/constraints/NotNull.html)使字段是必需的。 – 2014-09-06 19:08:15

回答

1

您必須在您的設置Constraints r Entity或者您可以在您的FormTypemanually中爲您的字段設置驗證規則。

這裏是你的`實體的例子

use Symfony\Component\Validator\Constraints as Assert; 

... 

/** 
    * @var string 
    * 
    * @ORM\Column(name="content", type="text") 
    * @Assert\NotBlank(
    *  message = "Your error message here if content is empty"  
    *) 
    */ 
private $content; 
+0

但我不想內容是可以爲空:)我希望它被驗證爲NOT爲空 – Leo 2014-09-06 19:17:49

+0

然後添加約束。 – 2014-09-06 19:18:11

+0

任何想法如何以後顯示此消息? – Leo 2014-09-06 19:26:03