2016-11-04 27 views
0

我正在轉向Symfony,並且驗證了我發送的發佈數據的問題。我按照官方的文檔,放在實體此屬性:Symfony驗證器不驗證發佈數據

/** 
* @ORM\Column(type="string", length=100) 
* @Assert\Length(
*  min = 3, 
*  max = 50, 
*  minMessage = "Your name must be at least {{ limit }} characters long", 
*  maxMessage = "Your name cannot be longer than {{ limit }} characters" 
*) 
*/ 
private $name; 

守則控制器:

$student = new Student(); 
    $student->setName($request->query->get('name')); 
    $student->setBirth_Date(new \DateTime($request->query->get('date'))); 

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

    if (count($errors) > 0) { 
     /* 
     * 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('Validation errors: '. $errorsString); 
    } 

    $em = $this->getDoctrine()->getManager(); 
    $em->persist($student); 

    // actually executes the queries (i.e. the INSERT query) 
    $em->flush(); 

    return new Response('Saved new student with id '. $student->getId()); 

爲什麼它不驗證,我總是得到在數據庫中的新項目嗎?我錯過了什麼嗎?

+0

嘗試發送一些無效的數據,並把var_dump($學生);後續代碼var_dump($錯誤);死(); '$ errors = $ validator-> validate($ student);'' 並請將結果粘貼到您的答案:) –

回答

0

請檢查這是你配置的驗證註解constrait,這樣說的:https://symfony.com/doc/current/validation.html#configuration 並清除緩存

app/console cache:clear 

或symfony3

bin/console cache:clear 
+0

仍然無法正常工作,您知道爲什麼嗎? – Nikanor

+0

也許你忘記命名空間添加'使用Symfony \ Component \ Validator \ Constraints as Assert;'到實體。 我試過你的代碼和它的工作 –

+0

不,我有那條線..只是不能在控制器中得到驗證。是否有另一種方法來加載驗證器?當我寫$ validator變量到日誌時,我得到空數組 – Nikanor

0

不得不把validation: { enabled: true, enable_annotations: false }的配置。沒有在文檔中找到它。 另外斷言NotBlank()之前需要進行第二次驗證。

/** 
    * @ORM\Column(type="string", length=100) 
    * @Assert\NotBlank() 
    * @Assert\Length(
    *  min = 3, 
    *  max = 50, 
    *  minMessage = "Your name must be at least {{ limit }} characters long", 
    *  maxMessage = "Your name cannot be longer than {{ limit }} characters" 
    *) 
    */