2016-11-04 5 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($ student);を入力してください。 var_dump($ errors);死ぬ(); '$ 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

ために、configでvalidation: { enabled: true, enable_annotations: false }を入れていました。ドキュメントでこれを見つけられませんでした。 また、2回目の検証が行われるまでに長さが必要となる前に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" 
    *) 
    */ 
関連する問題